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!
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With