I would like to redirect to the login page with an error message, when someone tried to access my admin page without authenticating, ie when someone tries to bypass the login page.
this is my admin
end point:
server.get('/admin', isLoggedIn, function (req, res) {
console.log('Trying to access admin section')
res.render('admin', {
user: req.user //get the user out of session and pass to template
})
});
which contains the following isLoggedIn
middleware:
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
console.log('Someone is trying to access this page without being authenticated')
req.flash('loginMessage', 'You need to be authenticated to access this page');
console.log(req.flash('loginMessage'))
res.redirect('/login')
}
the login
access point is defined as the following:
server.get('/login', function (req, res) {
console.log('Using login route');
res.render('login',
{message: req.flash('loginMessage')}
);
});
My problem is, when someone tries to access the admin
page directly, the flash message doesn't show up.
However when trying to login with fake credentials, the error messages do show up in the login page.
For information, this is how my post login route is set up:
server.post('/login', passport.authenticate('local-login', {
successRedirect:'/admin', // redirect to the secure profile section
failureRedirect:'/login', //redirect back to the login page if there is an error
failureFlash: true //allow Flash messages
}));
And I get the following messages in the terminal:
Someone is trying to access this page without being authenticated
[ 'You need to be authenticated to access this page' ]
GET /admin 302 8.859 ms - 68
Using login route
GET /login 200 79.373 ms - 1930
In connect-flash, when you are retrieving the flash messages set on a key with req.flash(<key>)
, it copies the messages of the <key>
to a temp array, DELETES the messages for that <key>
from the connect-flash's internal flash message store and then returns that temp array.
So the flash('loginMessage')
returns empty at route '/login', because you have previously retrieved it at isLoggedIn
's console.log(req.flash('loginMessage'))
.
I found it when I checked the sources of connect-flash. Its here : flash.js of connect flash. The exmples in there should give you the idea quickly.