使用没有flash消息的passportjs显示错误消息

时间:2017-08-16 07:32:12

标签: node.js passport.js

我使用护照本地策略进行身份验证,并在那里向用户返回一个json Web令牌。由于它现在是基于令牌的身份验证,因此我无法使用会话。我首先使用connect-flash获取并显示错误消息,但是当我使其无会话时,我在尝试使用flash消息时出错。它说:req.flash()需要会话。如何在不使用闪存消息的情况下获取和显示错误消息?请帮忙

passport.use('login', new LocalStrategy({
        passwordField : 'email',
        passReqToCallback : true
    },
    function(req, username, email, done) { 
        // check in mongo if a user with username exists or not
        User.findOne({ 'username' :  username }, 
            function(err, user) {
                // In case of any error, return using the done method
                if (err)
                    return done(err);
                // Username does not exist, log the error and redirect back
                if (!user){
                    console.log('User Not Found with username '+username);
                    return done(null, false, {message : 'user not found'});                 
                }
                // User exists but wrong password, log the error 
                if (!isValidPassword(user, email)){
                    console.log('Invalid Password');

                    return done(null, false, {message : 'Invalid password'}); // redirect back to login page
                }
                // User and password both match, return user from done method
                // which will be treated like success
                   var token = jwt.sign(user, 'secret');
                   req.token = token;
                   return done(null, user);
            }
        );

    })
);



var isValidPassword = function(user, email){
    return bCrypt.compareSync(email, user.email);
}

路线:

 router.get('/login',  (req, res) => {
    console.log(req.message);
    res.render('login');
});


 router.post('/signup', passport.authenticate('signup', { successRedirect: '/login',
                                                failureRedirect: '/signup'}));

router.post('/login', function(req, res, next) {
passport.authenticate('login', {session : false}, function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }

// if everything goes right return the token!
res.json({
    success : 'true',
    message : 'here is your token',
    token   : req.token

})

})(req,res,next); });

0 个答案:

没有答案