【发布时间】:2019-05-27 19:20:48
【问题描述】:
我在 GitHub 上查看了 bcrypt.compare 的其他问题,但没有一个解决方案对我有用。它总是在 bcrypt.compare() 内的 console.log("failed 3") 上失败
我已尝试切换 .then() 而不是按照另一篇帖子的建议使用带有 bcrypt.compare 的回调,但这没有帮助。任何帮助将不胜感激!
以下是我的代码副本和正在使用的版本摘要:
- 节点 v8.12.0
- Express 4.16.0
- bcrypt 3.0.3
- jsonwebtoken 8.4.0
- 猫鼬 5.4.1
Bcrypt 哈希(密码哈希)
function saveUserData(req, res, next, userSignUpInfo, info){
bcrypt.hash(req.body.email, 10, (err, hash) =>{
if (err){
return res.status(500).json({
error: err
})
} else {
console.log('inside test route')
console.log('req.body.fnUserName', userSignUpInfo.fnUserName)
const userData = new UserData({
fnUserName : userSignUpInfo.fnUserName,
password : hash,
email : req.body.email,
verify: userSignUpInfo.verify,
createAccountDate: userSignUpInfo.createAccountDate,
userId : userSignUpInfo.userId,
friends: null,
online: null
})
userData.save()
.then(result => {
console.log('result from MongoDB Cloud', result);
saveApiData(info, userSignUpInfo, res);
})
.catch(err => console.log('error from MongoDB Cloud', err));
}
})
}
Bcrypt 比较(验证用户)
router.post('/login', (req, res, next) => {
UserData.find({email: req.body.email})
.exec()
.then(user => {
if(user.length < 1) {
console.log("failed 1")
return res.status(401).json({
message: 'Authentication Failed'
});
}
console.log('user[0].password', user[0].password)
console.log(' user[0].password', user[0].password)
console.log(' req.body.password', req.body.password)
bcrypt.compare(req.body.password,user[0].password).then(function(err, result) {
if (err) {
console.log("failed 1")
return res.status(401).json({
message: 'Authentication Failed'
});
}
if (result) {
const token = jwt.sign(
{
email: user[0].email,
userId: user[0].userId
},
process.env.JWT_KEY,
{
expiresIn: "1h" // he suggested one hour
}
);
console.log("failed 2")
return res.status(200).json({
message: 'Authentication Successful',
token: token
})
} else {
console.log("failed 3")
res.status(401).json({
message: 'Authentication Failed'
})
}
})
})
.catch(err => {
console.log('err in login', err);
res.status(500).json({
error: err,
message: 'error logging in'
})
})
});
【问题讨论】:
标签: javascript node.js express jwt bcrypt