Update req.user in session

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 request.user contains the updated user details?

That is, after updating the database, how do I update the session info on the user as well?

I tried directly assigning the updated details to request.user but it did not work. I then tried request.session.passport.user - this worked but there is a delay of around 5 to 10 seconds before it gets updated in request.user too.

Is there a function that I need to call that updates the user information stored in the session? Or is there some other object that I can update where the change does not have a delay

 

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

 

Thank you for pointing this out. This seems to be the correct way to update the session data since login calls the passport serializer function that updates the user data stored in the session. However, for some reason, I experienced delays in updating the session so the res.send(200) equivalent code in my application was placed inside a setTimeout function of 2 seconds - that helped. – callmekatootie Jul 1 '14 at 13:25

  • Very weird. So if you do two console logs like in my example, the second one still shows the old data? You'd think by the time the req.login callback happens, every async change would have been performed. Well, if a 2 sec wait fixes it every time, you're good. – chichilatte Jul 1 '14 at 17:37

 

 

你可能感兴趣的:(WebDev)