我在比较密码时遇到问题,是的,当我注册时,它正确存储了密码的哈希值。
数据库-MongoDB 我正在使用 node.js 版本 - v18.17.0 bcrypt 版本 - 5.1.1
这是我的用户架构 -
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
userSchema.pre('save', async function (next) {
try {
if (!this.isModified('password')) {
return next();
}
const hashedPassword = await bcrypt.hash(this.password, 10);
this.password = hashedPassword;
return next();
} catch (error) {
...
}
})
这也是我的 AuthController.js 文件的登录部分 -
loginUser: async (req, res) => {
try {
const { email, password } = req.body;
const trimmedPassword = password.trim();
console.log('Password received:', password);
console.log('User password:', user.password);
const passwordMatch = await bcrypt.compare(trimmedPassword, user.password);
console.log(passwordMatch);
if (!passwordMatch) {
return res.status(401).json({ error: 'Invalid email or password.' });
}
// Generate a JWT token
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expireIn: '1h' });
res.json({ token, userId: user._id, username: user.username });
} catch(error){...}
我现在正在使用邮递员来检查它,邮递员给我错误:“无效的电子邮件或密码”,并且在终端中我收到 -
收到密码:abcd
用户密码:$2b$10$3XqxT29oUNX8Sr86i/woPufzHf6s7OjP4yyNdirtGk9Zj0T3MdkAC
假
loginUser: async (req, res) => {
try {
const { email, password } = req.body;
const user = await UserModel.findOne({ email: email });
if (!user) {
return res.status(401).json({ error: 'Invalid email or password.' });
}
const trimmedPassword = password.trim();
console.log('Password received:', password);
console.log('User password:', user.password);
const passwordMatch = await bcrypt.compare(trimmedPassword, user.password);
console.log(passwordMatch);
if (!passwordMatch) {
return res.status(401).json({ error: 'Invalid email or password.' });
}
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token, userId: user._id, username: user.username });
} catch(error) {
console.error(error);
res.status(500).json({ error: 'An error occurred during the login process.' });
}
}