Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 587
Manu Masson Avatar asked Nov 08 '15 15:11

Manu Masson


2 Answers

The link you referred to, persistent sessions with passport, mongodb and express, is talking about an old version of the express framework, the one you are using in your package.json, https://github.com/manu354/teecher/blob/master/package.json, "express": "~4.13.1", is very new.

You need to move these lines:

app.use(passport.initialize());
app.use(passport.session());

above a little, to be immediately beneath the app.use(session({...})

I would recommend that you follow this blog post, http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/, it will definitely help you

like image 96
mkinawy Avatar answered Oct 08 '22 09:10

mkinawy


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.

like image 39
flcoder Avatar answered Oct 08 '22 11:10

flcoder