Search code examples
javascriptnode.jssessionpassport-local

Passport Local strategy session using express in Node.js


I'm a newbie in Node.js and used passport-local strategy for login session. I already set up all things in my web app, but I'm having a big problem with session.

I tried multiple users can login to my web app at the same time, but there is a problem. One of users(ex. username is Paul) log in first, and then another user(Chris) is log in after, then Paul's view of my web app is changed to Chris' view.

I'm not sure you guys understand what I mean by that but here is one of my code in Node.js

app.get('/location', isLoggedIn, function(req, res){
  var user_temp = {user: ''};
  user_temp.user = global_username;
  res.render('location/index1', user_temp);
});

And below code is Passport local-Strategy

var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
  new LocalStrategy({
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true
    },
    function(req, email, password, done) {
      User.findOne({ 'email' :  email }, function(err, user) {
        if (err) return done(err);
        if (!user){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'No user found.'));
        }
        if (!user.authenticate(password)){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'Password does not Match.'));
        }
        var email_address = req.body.email;
        username_tmp = email_address;
        var username = email_address.substring(0, email_address.lastIndexOf("@"));
        global_username = username;
        pass = req.body.password;
        return done(null, user);
      });
    }
  )
);

I think the problem is because of global_username, so Paul can see Chris' view of location. However, I don't know how to get the user variable and put that into ejs for each users.

Can anybody help me out here....?

Thanks in advance!

P.S. If what I asked is confused, I can edit my question again and explain more...


Solution

  • You can't use globals, they get overwritten for each request which will result in exactly the issue that you're describing.

    Instead, if you have set up Passport and express-session correctly, Passport will provide the user data for each (authenticated) request through req.user:

    app.get('/location', isLoggedIn, function(req, res) {
      res.render('location/index1', { user : req.user });
    });
    

    You can also take a look at the passport-local example application to get an idea on how everything is connected.