更新会话中登录的用户详细信息

时间:2021-03-30 13:02:37

I am using PassportJS with ExpressJS.

我在ExpressJS上使用PassportJS。

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?

我需要更新登录的用户详细信息。虽然我在数据库中更新了这个,但是如何在会话中更新它,以便request.user包含更新的用户详细信息?

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.

我尝试直接将更新的详细信息分配给request.user,但它不起作用。然后我尝试了request.session.passport.user - 这有效,但是在request.user中更新之前还有大约5到10秒的延迟。

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

是否有一个我需要调用的函数来更新存储在会话中的用户信息?或者是否有一些其他对象我可以更新,其中更改没有延迟

1 个解决方案

#1


27  

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)...

似乎有用的是,保存新更新的用户后,请执行req.login(用户)...

// "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

线索在这里... https://github.com/jaredhanson/passport/issues/208

#1


27  

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)...

似乎有用的是,保存新更新的用户后,请执行req.login(用户)...

// "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

线索在这里... https://github.com/jaredhanson/passport/issues/208