Update logged in user details in session Update logged in user details in session express express

Update logged in user details in session


I've been hunting down an answer for this too. Never mentioned in any docs or tutorials!

What seems to work is, after saving your newly updated user, do req.login(user)...

// "user" is the user with newly updated infouser.save(function(err) {    if (err) return next(err)    // What's happening in passport's session? Check a specific field...    console.log("Before relogin: "+req.session.passport.user.changedField)    req.login(user, function(err) {        if (err) return next(err)        console.log("After relogin: "+req.session.passport.user.changedField)        res.send(200)    })})

The clue was here... https://github.com/jaredhanson/passport/issues/208


User.findById(req.user._id,function(err,doc){        req.logIn(doc,function(err1){                if(err1){ console.log("Error : "+err1) }                              else{                                    res.render("abc.ejs",{user:req.user});                                    console.log('Item Removed Successfully!!!');                              }                        });                  });

Here we are re-login the user
User => Mongoose Model


I had similar problem today and decided to share my findings, since i couldn't find similar answer.

The problem was that (copied from passport documentation) i was getting the user data directly from the token, that the user sent in the request. Which was of course outdated.

passport.use(new JWTStrategy({    jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),    secretOrKey   : CONFIG.JWT_SECRET  },  function (jwtPayload, cb) {    return cb(null, jwtPayload);  }));

while i should get the fresh user object from the database instead:

return User.findById(jwtPayload.id)  .then(user => {    return cb(null, user);  })  .catch(err => {    return cb(err);  });