node.js - 如何在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 = 如果用户名存在,则为原始密码
希望它能解决你的问题
推荐阅读
- aws-kms - AWS KMS 存储客户主密钥
- angular - 如何在Angular中将数据源作为输入传递?
- java - 无法从任何配置的存储库解析原型 org.apache.maven.archetypes:maven.architype.quickstart:1.1
- java - Eclipselink 加载对象和 JMS 序列化
- r - 在 R 中重新设置 HOME 目录
- java - 无法获得数据库连接,因为我无法将上下文传递给 DBManager
- sqlite - 在 TFDTable.Filter 表达式中使用时找不到 DATETIME 函数
- javascript - 为什么从 const 结果返回 **element** 作为错误?
- php - 如何从两个表中选择数据并将借方和贷方列中的余额相加(php)
- node.js - 如何在nodejs中将多个文件转换为zip?