1

当有人试图访问我的管理页面而不进行身份验证时,我想重定向到带有错误消息的登录页面,即当有人试图绕过登录页面时。

这是我的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
4

2 回答 2

2

在 connect-flash 中,当您使用 检索键上设置的 flash 消息时req.flash(<key>),它会将消息复制<key>到 temp 数组,<key>从 connect-flash 的内部 flash 消息存储中删除该消息,然后返回该 temp 数组。

因此,flash('loginMessage')在路由 '/login' 处返回空,因为您之前已在isLoggedIn's处检索到它console.log(req.flash('loginMessage'))

当我检查 connect-flash 的来源时,我发现了它。它在这里:连接 flash 的 flash.js。那里的例子应该很快给你这个想法。

于 2015-06-06T11:47:00.887 回答
0

如果有人遇到此问题并且所选答案不起作用,请考虑尝试以下操作。我遇到了同样的问题,但在任何阶段都没有使用 console.log 等“消耗”密钥。

有问题的代码版本如下。我在 POST 路由中调用了这些指令:

req.flash('errorMessage', errors.array().map(err => err.msg););
res.redirect('/profile');

errorMessage: req.flash('errorMessage')'profile' 的 GET 路由在其输入中呈现 EJS 模板。

对我有用的是将我的错误消息 ( errors.array().map(err => err.msg)) 分配给一个变量并将该变量传递给 connect-flash,如下所示:

var errMsgs = errors.array().map(err => err.msg);
req.flash('errorMessage', errMsgs);
res.redirect('/profile');

希望这可以帮助。

于 2018-11-09T17:29:38.913 回答