Update logged in user details in session

前端 未结 3 796
时光取名叫无心
时光取名叫无心 2020-12-30 23:35

I am using PassportJS with ExpressJS.

I need to update the logged in user details. While I do update this in the DB, how do I update it in the session too so that re

相关标签:
3条回答
  • 2020-12-30 23:59

    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 info
    user.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

    0 讨论(0)
  • 2020-12-30 23:59

    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);
      });
    
    0 讨论(0)
  • 2020-12-31 00:00
    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

    0 讨论(0)
提交回复
热议问题