我正在为我的应用开发身份验证模块。每当用户名和密码被发布到' / admin / login' Api它调用Auth控制器的登录功能。 此外,我使用mongoose模型从MongoDb查询并将找到的对象返回给变量。
auth.controller.js
var jwt = require('jwt-simple');
var bcrypt = require('bcrypt');
var User = require('../models/user.model.js');
var secret = require('../config.js').jwt_secret;
var auth = {
login : function (req, res) {
var username = req.body.username;
var password = req.body.password;
if (username === '' || password === '') {
res.status(401).json({message : 'Invalid Credentials'});
return;
}
var dbUserObj = auth.validate(username, password); // receives the User object returned from callback
console.log(dbUserObj); //displays 'undefined'
if (!dbUserObj) {
res.status(401).json({message : 'Invalid Username or Password'});
return;
}
if (dbUserObj) {
console.log('user found');
res.json(genToken(dbUserObj));
}
},
validate : function (user, pass) {
User.findOne({username : user}, function (err, user) {
if (err) {
return;
}
if (user==null) {
console.log('no user found');
return;
} else {
bcrypt.compare(pass, user.password, function (err,result) {
if (result == true) {
return user;
}
});
}
});
}
}
function genToken (user) {
var expires = expiresIn(7);
var token = jwt.encode({exp : expires},secret);
return {
token : token,
exp : expires,
user: user
}
}
function expiresIn (t) {
var dateObj = new Date();
return dateObj.setDate(dateObj.getDate() + numDays);
}
module.exports = auth;
dbUserobject变量接收validate函数返回的User对象。但如果我记录这个变量,它会显示' undefined' 我知道有回调问题,下一行代码运行,回调后返回对象dbUserObject变量被初始化,它总是发送响应'无效的用户名或密码'因为dbUserObject变得未定义。 我尝试过几种东西,但无法解决。
如何让它首先接收DbUserObj,然后决定是发送无效响应还是生成Json Web令牌。
谢谢,
答案 0 :(得分:0)
由于存在同步和异步功能的问题,因为您的auth.validate
表现为async而不是等待结果,因为哪个用户对象未定义,您可以解决这可以通过使用Promise
试试这个
var auth = {
login : function (req, res) {
var username = req.body.username;
var password = req.body.password;
if (username === '' || password === '') {
res.status(401).json({message : 'Invalid Credentials'});
return;
}
auth.validate(username, password)
.then(function(dbUserObj) { // `validate` returns a promise
console.log(dbUserObj); // Log the value once it is resolved
if (!dbUserObj) {
res.status(401).json({message : 'Invalid Username or Password'});
return;
}
if (dbUserObj) {
console.log('user found');
res.json(genToken(dbUserObj));
}
console.log(dbUserObj); //displays 'undefined'
}).catch(function(v) {
// Or do something else if it is rejected
// (it would not happen in this example, since `reject` is not called).
});
},
validate : function (user, pass) {
return new Promise(function(resolve, reject) {
User.findOne({username : user}, function (err, user) {
if (err) {
return;
}
if (user==null) {
console.log('no user found');
return;
} else {
bcrypt.compare(pass, user.password, function (err,result) {
if (result == true) {
return user;
}
});
}
});
// Only `delay` is able to resolve or reject the promise
setTimeout(function() {
resolve(user); // After 3 seconds, resolve the promise with user
}, 3000);
});
}
}