我使用Node.js
作为iPhone客户端的后端API服务器.我用Passport.js
来验证local strategy
.相关代码如下:
// This is in user.js, my user model
UserSchema.static('authenticate', function(username, password, callback) {
this.findOne({ username: username }, function(err, user) {
if (err){
console.log('findOne error occurred');
return callback(err);
}
if (!user){
return callback(null, false);
}
user.verifyPassword(password, function(err, passwordCorrect){
if (err){
console.log('verifyPassword error occurred');
return callback(err);
}
if (!passwordCorrect){
console.log('Wrong password');
return callback(err, false);
}
console.log('User Found, returning user');
return callback(null, user);
});
});
});
和
// This is in app.js
app.get('/loginfail', function(req, res){
res.json(403, {message: 'Invalid username/password'});
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/loginfail', failureFlash: false }),
function(req, res) {
res.redirect('/');
});
现在,我成功地将一个失败的登录重定向到/loginfail,在那里我将一些JSON发送回iPhone客户端.然而,这并没有足够的粒度.我希望能够将适当的错误发送回iPhone客户端,例如:"未找到用户"或"密码错误".用我现有的代码,我看不出这是如何实现的.
I tried to follow the examples for a custom callback on the passport.js site, but I just can't get it to work due to lack of node underst和ing. How could I modify my code so that I'd be able to send back a res.json with an appropriate error code/message?
我现在正在try 这样的事情:
// In app.js
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
console.log(info);
// *** Display message without using flash option
// re-render the login form with a message
return res.redirect('/login');
}
console.log('got user');
return res.json(200, {user_id: user._id});
})(req, res, next);
});
// In user.js
UserSchema.static('authenticate', function(username, password, callback) {
this.findOne({ username: username }, function(err, user) {
if (err){
console.log('findOne error occurred');
return callback(err);
}
if (!user){
return callback(null, false);
}
user.verifyPassword(password, function(err, passwordCorrect){
if (err){
return callback(err);
}
if (!passwordCorrect){
return callback(err, false, {message: 'bad password'});
}
console.log('User Found, returning user');
return callback(null, user);
});
});
});
但当我试图安慰的时候.日志(log)(信息),它只是说未定义.我不知道如何让这个自定义回调正常工作...任何帮助都将不胜感激!