使我输入了正确的密码,bcrypt 的比较方法也返回 false?"/>
为什么即使我输入了正确的密码,bcrypt 的比较方法也返回 false?
我正在使用 Postman 来测试登录 API。注册 API 工作正常并在将密码保存到数据库之前对密码进行哈希处理。但是当我尝试使用相同的凭据登录时,它说密码不匹配。
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 5
},
email: {
type:String,
required: true,
unique: true,
trim: true
},
password: {
type: String,
required: true,
trim: true,
lowercase: true,
minlength: 6
}
});
这是加密密码的中间件
userSchema.pre("save", async function (next) {
try{
const user = this;
if (!user.isModified("password")) {
return next();
}
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);
user.password = hash;
next();
}
catch (error) {
throw new Error(error);
}
});
这是登录功能。每当我输入正确的用户名和密码时,它都会说密码错误。
try{
const {username, password} = req.body;
const { error } = loginValidation.validate(req.body);
if (error) {
return res.status(400).json({ message: error.details[0].message, type: "error"});
}
const existingUser = await User.findOne({ username });
if (!existingUser){
return res.status(401).json({message:"Invalid username", type:"error"});
}
const passwordMatch = await bcryptpare(password, existingUser.password);
if(!passwordMatch){
return res.status(401).json({message:"Invalid password", type:"error"});
}
res.status(200).json({message: "Login successful", type:"success"});
}catch(error){
console.log(error.message + "Error from controllers/auth.js");
res.status(500).json({message:"Error authenticating user", type:"error"});
}
}```
回答如下:
看起来您正在将模式中的密码转换为小写。删除密码字段中的
lowercase: true
,然后重试。
更多推荐
为什么即使我输入了正确的密码,bcrypt 的比较方法也返回 false?
发布评论