How to generate unique session cookie for every users login using passport.js in express?

Viewed 281

Everyone, I am a new user and learner for express and passport, sorry for any mistakes in this post. Currently, the below code is generating the same session cookie for all the users.

passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());




app.get("/", function(req,res) {
  res.render("index");
});

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

app.get("/register", function(req,res) {
  res.render("register");
});

app.get("/logout", function(req, res) {
  req.logout();
  res.redirect("/");
});

app.post("/register", function(req, res) {


//We will be using Passport-local-mongoose for all registration and authentication as a middleman for us
User.register({username: req.body.username}, req.body.password, function(err, user) {
  if (err) {
    console.log(err);
    res.redirect("/register")
  } else {
    //If registered successfully, perform LOCAL Authentication - Nothing to UNDERSTAND here
    passport.authenticate("local")(req, res, function(){
        res.send("Done");
    });
  }
});

});

app.post("/login", function(req,res) {

const user = new User({
  username: req.body.username,
  password: req.body.password
});

//Login method from Passport
req.login(user, function(err) {
  if (err) {
    console.log(err);
    res.redirect("/login");
  } else {
    passport.authenticate("local")(req, res, function(){
        res.redirect("/users/" + user.username);
      });
  }
});
});

app.get("/users/:username", function(req,res) {

      if(req.isAuthenticated()) {
        User.findOne({username: req.params.username}, function(err,results) {
          if(!err){
            res.render("users/profile", {name: results.username});
          }
        });
      } else {
        res.redirect("/login");
      }

In this code at app.post("/register"), I am able to successfully register user say xyz@gmail.com and the same user(xyz@gmail.com( can also login successfully, and upon login xyz@gmail.com their URL in their browser changes to localhost:3000/users/xyz@gmail.com and can view their profile which contains order history and map as mentioned in the code, but however there is another registered user say 123@gmail.com which tries to enter localhost:3000/users/123@gmail.com who is automatically logged in and redirected to 123@gmail.com/profile because a session is already made for the user XYZ who was successfully logged in using the login page. So I am facing a problem that if one user is authenticated that session persists for all the other registered users also. what I want to achieve that if once the user is logged in it should have a unique session id and other registered users if they try to enter localhost:3000/users/123@gmail.com should be redirected to the login page and not automatically login.

0 Answers
Related