[英]Problem hashing password with bcrypt on node.js
I have the code below. 我有下面的代码。 I'm trying to hash my admin password when they get registered. 我正在尝试在注册时对我的管理员密码进行哈希处理。 The password initially is set to default via the mongoose schema. 最初通过猫鼬模式将密码设置为默认值。 Below are my codes. 以下是我的代码。 But it is not hashing. 但这不是散列。
AdminSchema.pre('save', function(next){
let admin = this; // bind this
if(admin.$isDefault('password')) {
bcrypt.genSalt(12, (err, salt)=> { // generate salt and harsh password
bcrypt.hash(admin.password, salt, (err, hash)=> {
admin.password = hash;
return next();
});
});
}
if(!admin.isModified('password')) {
return next();
}
bcrypt.genSalt(12, (err, salt)=> { // generate salt and harsh password
bcrypt.hash(admin.password, salt, (err, hash)=> {
admin.password = hash;
next();
});
});
});
It's because bcrypt method are execute asynchronously so for the first time this will be always executed 这是因为bcrypt方法是异步执行的,因此第一次将始终执行
if(!admin.isModified('password')) {
return next();
}
this should work 这应该工作
AdminSchema.pre('save', function(next) {
const admin = this // bind this
if (admin.$isDefault('password') || admin.isModified('password')) {
bcrypt.genSalt(12, (err, salt) => { // generate salt and harsh password
if (err) {
return next(err);
}
bcrypt.hash(admin.password, salt, (err, hash) => {
if (err) {
return next(err);
}
admin.password = hash
return next()
})
})
} else {
return next();
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.