sidonaldson
sidonaldson

Reputation: 25304

Passport update session isn't persisting

I'm trying to update my user session with a new name, an easy task I thought.

I'm a logged in user and in hitting a 'update' route and I've defined my own middleware to update the session:

module.exports = function(req, res, next) {
    console.log(req.user);
    req.login(req.body.user, function(err) {
       if (err) return next(new Error('Error updating user profile'));
       console.log('USER UPDATED *******', req.user);
       next();
    });
};

It took a bit of time to dig out the above code which should simply update the Passport session object. It correctly logs the previous session, and then the updated session but when I navigate to a new page after the inital response the user object is entirely lost and just returns {}.

Any ideas?

source

Upvotes: 0

Views: 536

Answers (1)

laggingreflex
laggingreflex

Reputation: 34667

To log in a user and persist it into session passport uses a serialize function which typically stores user.id as a cookie and a deserialize function which retrieves that cookie and does a User.findById database call to find the associated user, and if found one, that's the user object that gets stored in req.user.

req.login passes whatever you pass it as the first argument directly to passport.serialize, which otherwise would've typically come from a strategy, which itself would've retrieved the user object from a database call, or created one.

So when you use req.login you need to pass it the user object that passport.serialize actually would've received, so that it could store the id in a cookie.

In your case, you were doing req.login(req.body.user, ... and since req.body.user comes from a POST Form variable it must not have the id that passport.serialize would've stored in the cookie.

You should instead use the new values from req.body.user and update req.user itself, and then do req.login(req.user, ...

var  _ = require('lodash');
module.exports = function(req, res, next) {

    //using lodash merge the updated user into the cached user
    _.merge(req.user, req.body.user);

    req.login(req.user, function(err) {
       if (err) return next(new Error('Error updating user profile'));
       console.log('USER UPDATED *******', req.user);
       next();
    });
};

Upvotes: 2

Related Questions