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ページに直接アクセスしようとすると、フラッシュ メッセージが表示されないことです。ただし、偽の認証情報でログインしようとすると、ログイン ページにエラー メッセージが表示されます。詳細については、これが私のログイン後のルートの設定方法です。

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