node.js - Passport authenticate is always executing failureRedirect -
i using passport.js authenticate users node.js backend app. following code performing failureredirect , not able find reason it. there no error message.
router.post('/login', passport.authenticate('local', { failureredirect: '/users/login', failureflash: 'invalid email or password' }), function(req, res) { console.log('authentication successful'); req.flash('success', 'you logged in '); res.redirect('/'); });
i copied code passport website , not working:
router.post('/login', passport.authenticate('local', { successredirect: '/', failureredirect: '/users/login' }));
the following code not starting:
passport.use(new localstrategy({ email: 'email', password: 'password' }, function(email, password, done) { user.getuserbyemail(email, function(err, user) { if (err) throw err; if (!user) { console.log('unknown user'); return done(null, false, { message: 'unknown user' }); } user.comparepassword(password, user.password, function(err, ismatch) { if (err) throw err; if (ismatch) { return done(null, user); } else { console.log('invalid password'); return done(null, false, { message: 'invalid password' }); } }); }); }));
rest of relevant code:
passport.serializeuser(function(user, done) { done(null, user.id); }); passport.deserializeuser(function(id, done) { user.getuserbyid(id, function(err, user) { done(err, user); }); }); module.exports.getuserbyemail = function(email, callback){ var query = {email: email}; user.findone(query, function(err, user) { callback(err, user); }); } module.exports.getuserbyid = function(id, callback){ user.findbyid(id, function(err, user) { callback(err, user); }); } module.exports.comparepassword = function(userpassword, hash, callback){ console.log("pwd: " + userpassword + " hash: " + hash); bcrypt.compare(userpassword, hash, function(err, ismatch) { if(err) return callback(err); callback(null, ismatch); }); }
try changing localstrategy configuration this one
the default login variable name express uses 'username' , 'password'. in case have changed, 'email' in above case code should modified in following way:
passport.use(new localstrategy({usernamefield: 'email'}, function(username, password, done){ user.getuserbyemail(username, function(err, user){ //rest of code
without change in usernamefield, localstrategy searches 'username' not find hence, redirects. when usernamefield changed, finds 'email' , uses in place of username authentication.
Comments
Post a Comment