Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra information in user object in passport.js or somewhere in session

I want to add custom keys in the user object that is coming from mongodb and that is going to be used by passport.js but i wonder why i can't add more keys to that object, here is my code.

passport.use(new LocalStrategy(
    function(username, password, done) {
        Users.model(false).findOne( {email:username,password:encodePassword(password) }, function(err, user) {
            if( err ){ // validation failed
                console.log('Error Occurred');
                return done(err);
            }
            else if(user != null){

                user['customKey'] = "customValue"; // it is not setting

                console.log(user);

                return done(null, user);
            }
            else {

                return done(null, false, { message: 'Incorrect username.' });
            }
        });
    }
));
///Session handling
passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    Users.model(false).findById(id, function(err, user) {
        done(err, user);
    });
});
like image 927
Taimoor Avatar asked Oct 11 '13 08:10

Taimoor


1 Answers

See answer from another question:

Either in the deserialization function, before returning the user

passport.deserializeUser(function(id, done) {
    getUser(id).then(function(user) {
        user.whatever = 'you like';
        return done(null, user);
    });
});

or in an express middleware (before the router).

app.use(function(req, res, next) {
    if(req.user) req.user.whatever = 'you like';
    next();
});
like image 101
Nick Price Avatar answered Sep 24 '22 00:09

Nick Price