如何解决当我尝试比较时 Bcrypt 密码失败?
我是一个完整的编码初学者,目前正在学习 NodeJs,我已经被这种情况困扰了好几天了。 我正在尝试将 mongodb 中的散列密码与通过邮递员输入的用户进行比较。 我正在使用 bcrypt 将散列密码与原始字符串进行比较,但我得到了错误的陈述。 非常感谢任何帮助
这是猫鼬模型架构,
const useRSSchema = new mongoose.Schema({
name: {
type: String,required: true,trim: true,},email: {
type: String,unique: true,lowercase: true,validate(value) {
if (!validator.isEmail(value)) throw new Error("Invalid email");
},password: {
type: String,minLength: 7,validate(value) {
if (value.toLowerCase().includes("password")) {
throw new Error("Password should not consist of string 'password'.");
}
},})
useRSSchema.pre("save",async function (next) {
const user = this;
const saltRounds = 8;
if (user.isModified("password")) {
user.password = await bcrypt.hash(user.password,saltRounds);
}
next();
});
以下是登录路径;
router.post("/users/login",async (req,res) => {
try {
const user = await Users.findByCredentials(
req.body.email,req.body.password
);
res.send(user);
} catch (error) {
res.status(400).send(error);
}
});
下面是我尝试比较密码的地方,请帮助我找出错误的原因。
useRSSchema.statics.findByCredentials = async (email,password) => {
const user = await Users.findOne({ email: email });
if (!user) {
throw new Error("Unable to log in!");
}
const isMatch = await bcrypt.compare(password,user.password);
if (!isMatch) {
throw new Error("Unable to login");
}
return user;
};
解决方法
尝试使用 bcryptjs.hashSync() 和 bcryptjs.compareSync 代替
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。