如何强制刷新req.user?

时间:2014-02-21 22:54:25

标签: node.js session express passport.js

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

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

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

简化示例:

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 个答案:

答案 0 :(得分:8)

您应该能够在请求中调用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();
});