如何强制刷新req.user?

时间:2023-01-19 23:59:44

I am using passport.js with local authentication strategy for my node.js/express app.

我在我的node.js / express应用程序中使用带有本地身份验证策略的passport.js。

The user returned by LocalStrategy includes things like email and username.

LocalStrategy返回的用户包括电子邮件和用户名等内容。

I want to give users the ability to update their email or username within the app. When this happens, I'd like to tell passport to reload the user (similar to as if they had just logged in) so that req.user reflects the updated changes the remainder of the session. Simply setting it doesn't seem to last past that one request.

我想让用户能够在应用程序中更新他们的电子邮件或用户名。当发生这种情况时,我想告诉护照重新加载用户(类似于他们刚刚登录),以便req.user在会话的剩余部分反映更新的更改。简单地设置它似乎不会超过那个请求。

Simplified example:

简化示例:

app.get('/changeEmail', function(req, res, next) {

    var userId = req.user.id;
    var origEmail = req.user.email;
    var newEmail = req.param('email');

    userDao.updateEmail(userId, newEmail, function(err) {
        if (!err) {
            // user's email has changed, need change reflected in req.user from this point on
            req.user.email = newEmail;
        }
        next();
    });

});

1 个解决方案

#1


8  

You should be able to call the logIn method on the request. This will call the serializeUser method to update the session.

您应该能够在请求上调用logIn方法。这将调用serializeUser方法来更新会话。

userDao.updateEmail(userId, newEmail, function(err) {
    if (!err) {
        // user's email has changed, need change reflected in req.user from this point on
        var user = req.user;
        user.email = newEmail;
        req.logIn(user, function(error) {
            if (!error) {
                // successfully serialized user to session
            }
        });
    }
    next();
});

#1


8  

You should be able to call the logIn method on the request. This will call the serializeUser method to update the session.

您应该能够在请求上调用logIn方法。这将调用serializeUser方法来更新会话。

userDao.updateEmail(userId, newEmail, function(err) {
    if (!err) {
        // user's email has changed, need change reflected in req.user from this point on
        var user = req.user;
        user.email = newEmail;
        req.logIn(user, function(error) {
            if (!error) {
                // successfully serialized user to session
            }
        });
    }
    next();
});