Manu Manu - 4 months ago 16
Node.js Question

Passport isn't keeping persistent login sessions

I first looked at persistent sessions with passport, mongodb and express but it didn't help or make sense.

I'm trying to get persistent logins with my website. My serializing process is not working.

// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
//return the unique id for the user
return done(null, user._id);
});

//Desieralize user will call with the unique id provided by serializeuser
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('deserializing user:',user.username);
return done(err, user);
});
});


The whole passport file can be found on the github.

I think the problem is that I get deserialized immediately, or atleast thats what the console.logs show.

Or it could be with my session:

app.use(session({
secret: 'keyboard cat',
cookie : {
maxAge: 3600000 // see below
}
}));


Here's my user schema:

var userSchema = new mongoose.Schema({
username : String,
password : String, //Hash
created_at : {type: Date, default : Date.now}
});


Thanks for the help!

Answer

Your problem is not in passport or your back end. It's on the front end with angular. You are only setting $rootScope.authenticated when the user takes a login action, but you need to check with the server upon every app initialization by calling your api to see if the user has already logged in before.

So, perhaps, in routes/api.js create a router.route('/current_user') route which should either return null (or some kind of guest user object) or it will return the currently logged in user's info so that your front end angular app will know whether the user is logged in or not and have some user information to work with. If /api/current_user provides a user, then you know you're logged in and you can set $rootScope.authenticated = true.