Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only one user session is created instead of a new session for each different logged in user #1016

Open
skepticon7 opened this issue Jan 14, 2024 · 0 comments

Comments

@skepticon7
Copy link

Hello , I have a problem regarding my login application , im using passport-local strategy to authenticate users but the problem is that only one user session is created at the MongoStore , instead of a unique session for each logged in user , every single recently logged in user overwrites the old session and stores the ID in the only session that exists here is my code if anybody wants to help . Thank you

const express = require("express");
const mongoose = require("mongoose");
const BodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const LocalStrategy  = require("passport-local").Strategy;
const DBURL = "mongodb://127.0.0.1/SDB";

app = express();


mongoose.connect(DBURL).then(()=>{
    console.log("successfully connected to database");
}).catch((err)=>{
    console.log("error,connecting to database");
})

const sessionStore = MongoStore.create({
    mongoUrl : DBURL,
    collectionName : "sessionas"
});

const UserSchema = new mongoose.Schema({
    username: { type: String , required: true },
    email:String,
    password : String
}) ;

const User = new mongoose.model("User" , UserSchema);

app.use(BodyParser.urlencoded({extended:true}));
app.set("view engine","ejs");

app.use(session({
    secret:"SecretKey",
    saveUninitialized : false,
    resave:false,
    store : sessionStore
}));

passport.serializeUser(function(user, done) {
    done(null, user.id); 

});


passport.deserializeUser(function(id, done) {
    User.findById(id)
        .then(function(user) {
            if(user){
                done(null, user);
            }else{
                done(err, null);
            }
        })
        .catch(function(err) {
            done(err, null);
        });
});


app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(
    async function(username , password , done)
    {
        try {
            const data = await User.findOne({username : username});
            if (!data) {
                return done(null, false);
            }
            
            const isValidPassword = bcrypt.compare(password , data.password);
            if (isValidPassword) {
                return done(null,data);
               
            } else {
                
                return done(null, false);
            }
        } catch (error) {
            console.error(error);
            return done(error);
        }
    }
  ));

app.get("/",(req,res)=>{
    res.render("login");
})

app.post('/',passport.authenticate("local",{ failureRedirect: "/login" , successRedirect:"/secure" }));
    


app.get("/secure",(req,res)=>{
    res.send("welcome to secure route");
})

app.get("/signup",(req,res)=>{
    res.render("signup");
});

app.post("/signup" , async function(req,res){
    const un = req.body.username;
    const email = req.body.email;
    try {
        const hashedpsw = await bcrypt.hash(req.body.password,10);
        console.log(hashedpsw);
        const NewUser  = new User({
            username:un,
            email:email,
            password:hashedpsw
        });
        NewUser.save();

    } catch (error) {
        res.status(500).send("error internal server");
    }


    
    res.redirect("/");
});


app.listen(3000,()=>{
    console.log("server listening on port 3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant