[英]Unable to verify hashed password
Hi All , 大家好 ,
I am authenticating my user using bcrypt module . 我正在使用bcrypt模块对用户进行身份验证。
I am able to do perform the Registration process, but facing problem during Login process. 我能够执行注册过程,但是在登录过程中遇到问题。
User Model : 用户模型 :
var userSchema = new Schema({
email: {type: String, required: true},
password: {type: String,
});
Hashing methods : 散列方法 :
userSchema.methods.encryptPassword = function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(5), null)
};
userSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
Sign in : 登入 :
module.exports.login = function (user, callback) {
User.findOne({'email': user.email, 'password': user.validPassword(this.password)}, callback);
};
Login Route 登录路线
router.post('/login', function (req, res) {
var user = req.body;
User.login(user, function (err, user) {
if (err) {
throw err;
}
if (!user) {
res.sendStatus(404);
return;
}
res.json(user.id);
});
});
While executing am getting this error: TypeError:user.validPassword is not a function 执行时出现此错误: TypeError:user.validPassword不是一个函数
Please Help. 请帮忙。
In Login Route , you need to instantiate the Schema: 在Login Route中 ,您需要实例化Schema:
router.post('/login', function (req, res) {
var user = new User(req.body);
User.login(user, function (err, user) {
if (err) {
throw err;
}
if (!user) {
res.sendStatus(404);
return;
}
res.json(user.id);
});
});
Your mistake is that the user being provided to your login
method is not a Mongoose DB object. 您的错误是提供给您的
login
方法的用户不是Mongoose数据库对象。 Instead, your login function should look something like this: 相反,您的登录功能应如下所示:
module.exports.login = function (request, callback) {
User.findOne({'email': request.email }, function(err, user) {
if (err) return callback(err);
if(!user || !user.validPassword(request.password)) return callback();
return callback(null, user);
});
};
This will ensure that user
is a valid Mongoose object before you attempt to verify the password. 在您尝试验证密码之前,这将确保
user
是有效的Mongoose对象。
One other possible solution, if you'd prefer to avoid checking that the password is valid in your data layer, is to simply fetch the user document based on its email and then check the password in the login route. 如果您希望避免在数据层中检查密码是否有效,另一种可能的解决方案是简单地根据用户文档的电子邮件获取用户文档,然后在登录路径中检查密码。
router.post('/login', function (req, res) {
var user = req.body;
User.findOne(user, function (err, user) {
if (err) {
throw err;
}
if (!user) {
res.sendStatus(404);
return;
}
if (!user.validPassword(req.body.password)) {
res.sendStatus(401);
return;
}
res.json(user.id);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.