我正在尝试实现正常的登录和注册模块,并且我在理解done函数方面遇到了困难。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。而不是我想知道何时出现错误并想发送我的自定义消息。
答案 0 :(得分:3)
我不知道你是什么意思
访问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'
});
}
答案 1 :(得分:0)
另一种方法。 我不知道我是多么想念它。文档中有一个自定义回调选项。这是相同的实现。
app.post('/user/auth/login', function(req, res) {
passport.authenticate('local-login', function(err, user, info) {
if (err) {
res.status(500).send(JSON.stringify({
'msg': "Internal Server Error"
}));
}
if (!user) {
res.status(401).send(JSON.stringify({
'msg': "Username or Password is incorrect"
}));
}
if (user) {
res.status(200).send(JSON.stringify({
'msg': "Successfully logged in"
}));
}
})(req, res, next);
});
此解决方案的唯一问题是您必须手动登录并创建会话以及所有这些。
- 可以提供可选的
callback
以允许应用程序覆盖身份验证尝试的默认方式 处理。回调具有以下签名,其中user
将成功设置为已通过身份验证的用户 身份验证尝试,否则为false
。可选info
参数将被传递,包含由其提供的其他详细信息 策略的验证回调。
app.get('/protected', function(req, res, next) {
passport.authenticate ('local',function(err, user, info) {
if (err) { return next(err) }
if (!user) { return res.redirect('/signin') }
res. redirect('/account');
})(req, res, next);
});
请注意,如果提供了回调,则应用程序有责任登录用户,建立会话,否则 执行所需的操作。