lucia-auth / lucia

Authentication, simple and clean
https://lucia-auth.com
MIT License
8.32k stars 447 forks source link

[Bug]: Session validate response is null, validateSession returns null #1572

Closed yashwanth2804 closed 1 month ago

yashwanth2804 commented 1 month ago

Package

lucia

Describe the bug

import { Lucia, TimeSpan } from "lucia";
import { MongodbAdapter } from "@lucia-auth/adapter-mongodb";
import { Collection, MongoClient, ServerApiVersion } from "mongodb";

// Replace the placeholder with your Atlas connection string
const uri = ""

// const client = new MongoClient();
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
});
await client.connect();

const db = client.db();
const User = db.collection("users");
const Session = db.collection("sessionsDB");

const adapter = new MongodbAdapter(Session, User);

export const lucia = new Lucia(adapter, {
  sessionExpiresIn: new TimeSpan(2, "w"), // 2 weeks
  sessionCookie: {
    attributes: {
      // set to `true` when using HTTPS
      secure: process.env.NODE_ENV === "production",
    },
  },
});

app.post("/login", async (req, res) => {
  const { username, password } = req.body;

  const userId = generateIdFromEntropySize(10); // 16 characters long
  const session = await lucia.createSession(userId, {});

  // validate session
  console.log("@@ sessionID", session.id);
  const { session: session1, user } = await lucia.validateSession(session.id);
  console.log("session", session1);

  // If everything is ok, return the user
  res.json({ username, userId, session, session1 });
});

im not using monnoge here , but I can be able to see the SessionDB collection and document , saving the ssession values

_id : "t5qopbq7wjyjonsuyijqwtpko2vlykj6gwbunbem"
user_id:"b6ixgs555blwu5gt"
expires_at:2024-06-02T10:31:52.101+00:00

Postman Output

{
    "username": "www",
    "userId": "b6ixgs555blwu5gt",
    "session": {
        "id": "t5qopbq7wjyjonsuyijqwtpko2vlykj6gwbunbem",
        "userId": "b6ixgs555blwu5gt",
        "fresh": true,
        "expiresAt": "2024-06-02T10:31:52.101Z"
    },
    "session1": null
}

there is no users collection created, only sessionsDB

yashwanth2804 commented 1 month ago

But what working is this part of code where I can query based on user session


// get user session endpoint
app.get("/user/:userId", async(req: Request, res: Response) => {
  const userId = req.params.userId;
  const userSession = await lucia.getUserSessions(userId);
  res.json({ userSession });
});

after session expire time i get [] else gets the session obj.

This doesnot scale well becasue user can have multiple sessions from multiple devices

pilcrowOnPaper commented 1 month ago

This is expected behavior. Lucia considers sessions without valid user IDs as invalid

yashwanth2804 commented 1 month ago

HI @pilcrowOnPaper , I am sorry but my session have the userID in it , following is mongodb atlas sc image

this ie my session object console.log

session {
  id: 'c3vtkvbkwopfsqqwioujvzzewuoqirrku2jeellg',
  userId: 'mi5zb3ndx67te7ad',
  fresh: true,
  expiresAt: 2024-05-20T05:03:01.465Z
}
@@ sessionID c3vtkvbkwopfsqqwioujvzzewuoqirrku2jeellg

it is got the userID in it , can you please explain what Lucia considers sessions without valid user IDs as invalid means

So , Do i need to save the Users in mongodb , as far as I know lucia new version don't involve in user managment ?

yashwanth2804 commented 1 month ago
// luci.ts
import { Lucia ,TimeSpan} from "lucia";

import { MongodbAdapter } from "@lucia-auth/adapter-mongodb";
import { Collection, MongoClient, ServerApiVersion } from "mongodb";

// Replace the placeholder with your Atlas connection string
const uri = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"

// const client = new MongoClient();
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
});
await client.connect();

const db = client.db("session_db");
const User = db.collection("users") as Collection<UserDoc>;
const Session = db.collection("sessions")  as Collection<SessionDoc>;;

const adapter = new MongodbAdapter(Session, User);

export const lucia = new Lucia(adapter, {
    sessionExpiresIn: new TimeSpan(10, "d"), // 2 weeks
    sessionCookie: {
        attributes: {
            // set to `true` when using HTTPS
            secure: process.env.NODE_ENV === "production"
        }
    }
});

// IMPORTANT!
declare module "lucia" {
    interface Register {
        Lucia: typeof lucia;
    }
}

interface UserDoc {
    _id: string;
}

interface SessionDoc {
    _id: string;
    expires_at: Date;
    user_id: string;
}

Express api

import express, { Express, Request, Response } from "express";
import { generateIdFromEntropySize } from "lucia"; 
import { lucia } from "./luci";

const app: Express = express();
const port =   3002;

app.get("/", async(req: Request, res: Response) => {
  const userId = generateIdFromEntropySize(10); // 16 characters long
  const session = await lucia.createSession(userId, {});
  console.log("session", session);
  res.json({ userId,session});
});

// get user session endpoint
app.get("/session/:sessionID", async(req: Request, res: Response) => {
  const sessionID = req.params.sessionID;

  const { session, user } = await lucia.validateSession(sessionID);
  console.log("session  ", session);

  res.json({  session });
});

app.listen(port, () => {
  console.log(`[server]: Server is running at http://localhost:${port}`);
});

postman response

localhost:3002/

{
    "userId": "dempht5oflxddlnq",
    "session": {
        "id": "5nnqibdtt5a6d3f5ydpgepuzwfvidpnw3syvyoyy",
        "userId": "dempht5oflxddlnq",
        "fresh": true,
        "expiresAt": "2024-05-30T05:56:49.433Z"
    }
}

localhost:3002/session/5nnqibdtt5a6d3f5ydpgepuzwfvidpnw3syvyoyy

{
    "session": null
}
pilcrowOnPaper commented 1 month ago

Valid user IDs = a user with that user ID exists in your DB.

So , Do i need to save the Users in mongodb

So yes