I figured out my problem. The problem lied within my local strategy and my validPassword
prototype.
Within my strategy I had a console.log
saying error, invalid username or error, invalid password. I also had a console.log
in my prototype
printing the evaluation of passwordHash.verify(unhashedPassword, this.password)
.
When I posted to login the console would print as follows:
LOG: valid username (Strategy)
LOG: invalid password (Strategy)
LOG: true (Prototype)
following the flow of logic, LOG: true (prototype)
should appear before LOG: invalid password (Strategy)
but it was appearing after which means there was a problem with sync somewhere.
Well, I fixed the problem by removing about 15 lines of code and now it works like a beaut.
This is what my auth strategy looks like now.
User.prototype.validPassword
User.prototype.validPassword = function(unhashedPassword) {
return passwordHash.verify(unhashedPassword, this.password);
};
LocalStrategy
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
var unhashedPassword = password;
var passedUsername = username;
process.nextTick(function () {
User.findOne({ username: passedUsername }, function(err, user) {
console.log('within local strategy', user);
if (err) {
console.log('Error:', err);
return done(err);
}
if (!user) {
console.log('Incorrect username:');
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(unhashedPassword)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
});
}
));
POST Login
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});