我在MERN项目(Node v8.10.0)中使用bcrypt(v2.0.1),使用Mongoose在MongoDB中存储用户密码。哈希函数:
SellerSchema.pre('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
身份验证部分:
SellerSchema.statics.authenticate = function (email, password, callback) {
Seller.findOne({ email: email })
.exec(function (error, user) {
if (error) return callback(error);
else if (!user) {
var err = new Error('User not found.');
err.status = 401;
return callback(err);
}
bcrypt.compare(password, user.password).then(function (result){
if (result == true) {
return callback(null, user);
} else {
return callback();
}
});
});
};
登录路线:
router.post('/login', function(req, res, next) {
if (req.body.email && req.body.password){
Seller.authenticate(req.body.email,req.body.password,function(error,user) {
if (error || !user) {
console.log("this "+error);
var err = new Error('Wrong email or password.'); // logged everytime the compare result was false
err.status = 401;
return next(err);
} else {
res.json(user);
}
});
} else {
var err = new Error('Email and password are required.');
err.status = 401;
return next(err);
}
});
注册新用户时,哈希值存储得很好。使用纯文本登录几次传递compare(),但之后返回false。
如果我注册一个新用户并登录,它会再次运行一段时间然后开始返回false。 例如:我仍然可以登录在几小时前注册的用户(10-15比较)但无法登录在几分钟前创建的用户(1-2比较后)
使用Node:8.10.0,OS:Ubuntu 18.04
答案 0 :(得分:2)
每次保存对象时,pre('save')
中间件都在更新密码。要停止使用mongoose的isModified
函数,如下所示:
SellerSchema.pre('save', function(next) {
if (this.isModified('password')) { // check if password is modified then has it
var user = this;
bcrypt.hash(user.password, 10, function(err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
} else {
next();
}
});