I've got Passport setup to authenticate users stored in mongodb. Seems to work fine: authentication succeeds/fails appropriately and session variables get set. However, getting Passport to check for a session is failing. Something seems to be quite wrong in that the console.log statements I've added to the deserializeUser
callback never see the light of day. I assume my problem is related to deserializeUser
never being called. Anyone able to diagnose my misstep?
// Passport configuration
passport.serializeUser(function(user, cb){ cb(null, user.id) });
passport.deserializeUser(function(uid, cb){
console.log("Trying to deserialize user: "+uid);
User.findById(uid, function(err, user){
cb(err, user);
});
});
// auth strategy function
passport.use(new LocalStrategy({usernameField: 'email'},
function(email, pass, done){
User.findOne({email: email}, function (err, user) {
if (err)
return done(err);
if (!user)
return done(null, false, {message: "Couldn't find user"});
var crypted = bcrypt.hashSync(pass, user.salt);
if(user.hashpass != crypted)
return done(null, false, {message: "Bad password"});
return done(null, user);
});
}
));
passport.CreateSession = function (req, res, next) {
passport.authenticate('local', function(err, user, info){
if(err || !user)
return res.json({status: "Failure: "+err});
req.logIn(user, function (err){
if(err)
return res.json({status: "Failure: "+err});
return res.json({status: "Authenticated"});
});
})(req, res, next);
};
with the following in app.js:
app.post('/session', passport.CreateSession); // restify better
app.del('/session', passport.DestroySession);
app.get('/images', passport.CheckSession, routes.images);