'Why does the passport.js create an Unauthorized page on its own when authentication fails? how can I redirect it to a special page?
here is my router:
router.post('/login',
passport.authenticate('local'),
(req, res, next) => {
body('backurl').trim().escape();
let referrer = req.get('Referrer')
if (!req.user) {
return res.render('login', {
message: 'Unable to login, the password or the username are wrong',
backUrl: referrer
});
}
if (req.body.backurl == null || req.body.backurl == 'http://localhost:3000/signup' || req.body.backurl == 'http://localhost:3000/login') {
return res.redirect('/yourcourses');
}
return res.redirect(req.body.backurl);
}
);
When the user and the local authentication works it does work perfectly, however on fail I want to render the login page again with a message and a variable, however on failure the website simply makes an empty page with the word "unauthorized" on it without anything else, how do I fix it? thanks!
Solution 1:[1]
When authentication in Passport fails, the next() function is not called, the middleware chain is stopped and a generic error is returned, that's why your code isn't executing.
The solution could be to create another route, for example '/loginfail', and moving in there the code that re-renders the 'login' page with the referrer and the error message.
Then, modify the call to passport.authenticate to include an options object, like this:
passport.authenticate('local', { failureRedirect: '/loginfail' });
So, when authentication fails, Passport calls the route you specified.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JuanDeLasNieves |
