在未登录时尝试访问路由时使用connect-flash消息重定向

时间:2015-06-05 03:08:56

标签: node.js express passport.js connect-flash

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

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

2 个答案:

答案 0 :(得分:2)

在connect-flash中,当您检索使用req.flash(<key>)的密钥上设置的Flash消息时,它会将<key>的消息复制到临时数组,删除该消息{{1来自connect-flash的内部flash消息存储区,然后返回该临时数组。

所以<key>在路线'/ login'返回空,因为您之前已在flash('loginMessage')的{​​{1}}检索到它。

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

答案 1 :(得分:0)

万一有人来了,选择的答案不起作用,请考虑尝试以下方法。我遇到了同样的问题,但是在任何阶段都没有使用console.log等“消耗”密钥。

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

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

“配置文件”的GET路由在输入中包含errorMessage: req.flash('errorMessage')的EJS模板。

对我有用的是将错误消息(errors.array().map(err => err.msg))分配给一个变量,然后将该变量传递给connect-flash,就像这样:

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

希望这会有所帮助。