[英]mongoose and bcrypt-nodejs not hashing and saving password
我正在使用 bcrypt-node 和 mongoose 来散列用户密码并将该用户保存到 mongo 数据库。 当我调试下面的代码时,它似乎工作正常,当您在代码中记录密码时,它显示它是散列的,但是当您检查数据库时,它仍然是纯文本。 我对 node 和 mongoose/mongodb 比较陌生,所以我不确定如何进行故障排除。 我试过改变调用next();
return next(user);
正如另一篇文章中所建议的那样,但这没有帮助。 任何帮助将不胜感激。
我正在使用节点版本 6.9.5、猫鼬 4.7.0、bcrypt-nodejs 0.0.3 和 mongo 3.2.10
UserSchema.pre('save', function (next) {
var user = this;
if (user.password != "") {
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) {
return next(err);
}
console.log(hash);
user.password = hash;
console.log(user.password);
next();
});
});
} else {
return next();
}
}
return next();
});
您将哈希函数放在 genSalt() 函数之外。 此外,您使用了一些难以遵循的嵌套和条件。 尝试以下操作,看看它是如何工作的。
UserSchema.pre('save', function(next) {
const user = this;
if (!user.isModified('password')) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, null, (error, hash) => {
if (error) {
return next(error);
}
console.log('HASH: ', hash);
user.password = hash;
console.log('USER.PASSWORD: ', user.password);
next();
});
});
});
更具可读性,对吧?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.