Aaron Silverman
Aaron Silverman

Reputation: 22645

how can I force a refresh of req.user?

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

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

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.

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();
    });

});

Upvotes: 9

Views: 3402

Answers (1)

codelark
codelark

Reputation: 12334

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

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();
});

Upvotes: 8

Related Questions