I am trying to login the user with passport.js authentication and on success I redirect the user to the last page that comes from a variable inside the login page, and on failure I re-render the login page with a message, I tried to do it but I fail, here what I did:
router.post('/login',
body('backurl').trim().escape(),
(req,res,next) =>{
passport.authenticate('local', (err,user)=>{
if(err){return next(err)}
if(!user){
return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
}
if(req.body.backurl == null){
return res.redirect('/yourcourses')
}
return res.redirect(req.body.backurl)
});
}
);
it just keeps endlessly loading and nothing comes out, what is wrong with my code?
Thanks!
I can't seem to find a definitive reference for passport.authenticate, but all the example in https://www.passportjs.org/concepts/authentication/ show it as a middleware, so I think you'll need to use it as such:
router.post('/login',
passport.authenticate('local'),
(req, res, next) => {
req.body('backurl').trim().escape();
if (!req.user) {
return res.render('login', {
message: 'Unable to login, the password or the username are wrong'
});
}
if (req.body.backurl == null) {
return res.redirect('/yourcourses');
}
return res.redirect(req.body.backurl);
}
);