node.js - 了解 PassportJS 中的 done 函数

标签 node.js passport.js passport-local

我正在尝试实现一个正常的登录和注册模块,但我很难理解完成的功能。 here是我觉得负责完成功能的那一行。现在我想做的是返回相应的消息,就像出现服务器错误一样。

app.post('/user/auth/login', passport.authenticate('local-login'), function(req, res) {
    console.log("Login Request Successful");
    if(req.user){
        res.status(200).send(JSON.stringify({
            'msg' : "Successfully logged in"
        }));
    }
    else{
        res.status(400)
    }
    //console.log(req.user);
});

这是针对登录后 Passport 将用户对象附加到请求模块的情况。 但是如何区分服务器错误和身份验证失败错误

这是我的身份验证中间件。

passport.use('local-login', new LocalStrategy({
    passReqToCallback: true
}, function(req, username, password, done) {

    Users.findOne({
        'emailId': username
    }, function(err, user) {
        if (err)
            return done(err);
        if (!user)
            return done(null, false);
        else if (passwordHash.verify(password, user.password)) {
            console.log("User is verified");
            req.session.save();
            return done(null, user);

        } else
            return done(null, false);
    });
}));

基本上,我需要访问 done() 函数中的消息。我怎么做?

功能如何,比如如果我输入错误的密码,我在浏览器中收到的消息是未经授权的。这意味着它在某处将 response.data 字段设置为 Unauthorized。相反,我想知道何时出现错误并想发送我的自定义消息。

最佳答案

我不知道你是什么意思

access the messages in done() function

,但是您可以很好地在 done 回调中为添加对象提供消息

if (!user) {
    return done(null, false, {
                message: 'Unknown user or invalid password'
    });
}
if (!user.authenticate(password)) {
    return done(null, false, {
                message: 'Unknown user or invalid password'
    });
}

关于node.js - 了解 PassportJS 中的 done 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35574452/

相关文章:

node.js - Passport-Twitter - 错误 : Failed to find request token in session

javascript - Passport - 无法读取属性 'isAuthenticated'

node.js - VS 2015 Gulp 无法加载消息

node.js - 安装我的依赖项的开发依赖项

node.js - 如何在 NodeJS 中访问子进程的套接字?

Node.js 和 Backbone.marionette 初始 View

javascript - Flash 消息未显示在页面重定向上

javascript - PassportJS session 不适用于自定义回调

node.js - 如何持 Passport 开会?

javascript - 与两个单独文件中的本地策略 Passport 发生冲突