Giter VIP home page Giter VIP logo

Comments (5)

pilcrowOnPaper avatar pilcrowOnPaper commented on August 27, 2024 1

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

from lucia.

yashwanth2804 avatar yashwanth2804 commented on August 27, 2024

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

from lucia.

pilcrowOnPaper avatar pilcrowOnPaper commented on August 27, 2024

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

from lucia.

yashwanth2804 avatar yashwanth2804 commented on August 27, 2024

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 ?

from lucia.

yashwanth2804 avatar yashwanth2804 commented on August 27, 2024
// 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
}

from lucia.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.