Node.js 我尝试比较时Bcrypt密码失败?
我是一个完全的编码初学者,目前正在学习NodeJs,我被这种情况困扰了好几天。 我试图将mongodb中的散列密码与用户通过postman输入的密码进行比较。 我使用bcrypt将散列密码与原始字符串进行比较,但得到的却是错误的语句。 非常感谢您的帮助 这是猫鼬模型模式Node.js 我尝试比较时Bcrypt密码失败?,node.js,bcrypt,Node.js,Bcrypt,我是一个完全的编码初学者,目前正在学习NodeJs,我被这种情况困扰了好几天。 我试图将mongodb中的散列密码与用户通过postman输入的密码进行比较。 我使用bcrypt将散列密码与原始字符串进行比较,但得到的却是错误的语句。 非常感谢您的帮助 这是猫鼬模型模式 const usersSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true, }, e
const usersSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
unique: true,
required: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) throw new Error("Invalid email");
},
},
password: {
type: String,
required: true,
trim: true,
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相反我想知道,如何保存和更新用户。您的“save”钩子有一个问题。“save”钩子不会在update和findOneAndUpdate上执行。因此,当更新密码时,它不会被散列。您应该使用其他钩子,如
updateOne
或findOneAndUpdate
。我已经尝试将钩子findOne更改为findOneAndUpdate,但结果仍然是相同的false。而且似乎bcrypt每次都生成不同的哈希,即使我输入相同的字符串。因此,在比较之前,这将永远不会匹配。只需将console.logpassword
和user.password
进行比较,并确保这些值是您期望的值。这样你可以缩小问题的范围是的,这些值是不同的,不明白为什么console.log(user.password)
/$2a$08$hnfxw2ws.jznauegxrty.mlrfcwjkatwb/a580lbeu51gvzbzvyiconsole.log(wait bcrypt.hash(password,8))
/$2a$08$7fd4nhw6lv2absmcf7n20oyvgugzslfukafqymevytu6jw