登录时密码错误-Bcrypt



我正在使用mongooseexpress进行登录路由。当我创建一个帐户时,密码会被bcrypt散列。当我登录时,我需要对它们进行比较。下面是我的尝试:

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const UserSchema = new mongoose.Schema(
{
email: {
type: String,
required: [true, "L'e-mail est requis"],
unique: true
},
password: {
type: String,
required: [true, "Le mot de passe est requis"]
},
firstname: {
type: String,
required: [true, "Le prénom est requis"]
},
lastname: {
type: String,
required: [true, "Le nom est requis"]
}
},
{ collection: "users" }
);
UserSchema.pre("save", async function(next) {
const user = this;
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);
user.password = hash;
next();
});
UserSchema.methods.isValidPassword = async function(password) {
const user = this;
const compare = await bcrypt.compare(password, user.password);
return compare;
};
module.exports = mongoose.model("User", UserSchema);

问题是,我的路线返回";密码错误";。这是控制器:

module.exports.signIn = async (req, res) => {
const { email, password } = req.body;
const user = await UserModel.findOne({ email });
if (!user) {
return res.status(400).json({
message: "email not found."
});
}
if (user.password !== password) {
return res.status(400).json({
message: "wrong password."
});
}
res.status(200).json({
message: "User signed in."
});
};

就好像我的请求没有通过UserSchema.methods.isValidPassword。知道为什么吗?

此块:

if (user.password !== password) {
return res.status(400).json({
message: "wrong password."
});
}

只需将请求中的密码与数据库中存储的hash密码进行比较即可。条件是真的,所以你有消息";错误密码";。

您需要显式调用方法isValidPassword

const isValidPassword = await user.isValidPassword(password);
if (!isValidPassword) {
return res.status(400).json({
message: "wrong password."
});
}

快速补充说明:您不应该有两条不同的电子邮件消息未找到并且密码错误。这允许用户知道电子邮件是否存在并执行暴力攻击。我建议像";电子邮件或密码不正确";相反

最新更新