如何解决如何在sails js架构中使用bcrypt.compare?
module.exports = {
attributes: {
email: {
type: 'string',isEmail: true,unique: true,required: true
},password: {
type: 'string',required: true
}
},beforeCreate: (value,next) => {
bcrypt.hash(value.password,10,(err,hash) => {
if (err){
throw new Error(err);
}
value.password = hash;
next();
});
},};
现在当我想在登录时匹配密码时,我该如何解密密码,如果可能的话,我更愿意在用户模型文件中执行。
控制器/login.js
module.exports = {
login: async (req,res) => {
try{
const user = await User.findOne({email: req.body.email});
if (!user){
throw new Error('Failed to find User');
}
// here I want to match the password by calling some compare
//function from usermodel.js
res.status(201).json({user: user});
}catch(e){
res.status(401).json({message: e.message});
}
},};
解决方法
首先尝试通过用户找到给定用户名的用户
const find = Users.find(user=>user.username===req.body.username)
if(!find){
res.send('User Not Found')
}
else{
if( await bcrypt.compare(req.body.password,find.password)){
//now your user has been found
}
else{
//Password is Wrong
}
}
你必须使用 bcrypt.compare(a,b)
a = 用户给定的密码
b = 原始密码(如果用户名存在)
希望它能解决您的问题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。