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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值