当有人试图访问我的管理页面而不进行身份验证时,我想重定向到带有错误消息的登录页面,即当有人试图绕过登录页面时。
这是我的admin
终点:
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
})
});
其中包含以下isLoggedIn
中间件:
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')
}
login
接入点定义如下:
server.get('/login', function (req, res) {
console.log('Using login route');
res.render('login',
{message: req.flash('loginMessage')}
);
});
我的问题是,当有人尝试admin
直接访问该页面时,不会显示 Flash 消息。但是,当尝试使用虚假凭据登录时,错误消息会显示在登录页面中。有关信息,这是我的登录后路由的设置方式:
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
}));
我在终端中收到以下消息:
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