Node.js 如何在sails js模式中使用bcrypt.compare?
我有这样一个用户模型:Node.js 如何在sails js模式中使用bcrypt.compare?,node.js,mongodb,sails.js,bcrypt,sails-mongo,Node.js,Mongodb,Sails.js,Bcrypt,Sails Mongo,我有这样一个用户模型: module.exports = { attributes: { email: { type: 'string', isEmail: true, unique: true, required: true }, password: { type: 'string', required: true } }, beforeCreate: (value, next)
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();
});
},
};
现在,当我想在登录期间匹配密码时,如何解密密码,如果可能的话,我希望在用户模型文件中执行
controller/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=用户名存在时的原始密码
希望它能解决您的问题谢谢,这段代码运行得很好,但我想在编写模式的同一文件中编写比较函数,而不是在控制器中。这方面有什么帮助吗?我不确定这一点,但您可以使用2个参数创建函数,并将它们交给ByScript。在您的函数中进行比较,因此当您调用此函数时,您必须看到相同的结果