从数据库加载时哈希密码不匹配



我试图用我的凭据登录,但在从数据库加载后匹配密码时,如果仍然密码正确,则总是返回False。

登录路线-

router.post('/users/login', async (req, res) => {
// console.log(req.body.email)
// console.log(req.body.password)
try {
const user = await User.findByCredentials(req.body.email, req.body.password)
res.send(user)
} catch (e) {
res.status(400).send(e)
}
})

架构预存

userSchema.pre('save', async function (next) {
const user = this
if (user.isModified('password') || user.isNew) {
user.password = await bcrypt.hash(user.password, 8)
}
next()
})

使用凭据(电子邮件和密码(登录-

userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email: email })
// console.log(user)
if (!user) {
throw new Error('Unable to login')
}
const hashedPwd = await bcrypt.hash(password, 8);
console.log(hashedPwd)
const isMatch = await bcrypt.compare(password, user.password)
console.log('Password Match', isMatch)
if (!isMatch) {
throw new Error('Unable to login')
}
return user
}

用户架构-

const User = mongoose.model('User', {
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true
},
age: {
type: Number,
default: 0
},
password: {
type: String,
required: true,
trim: true,
lowercase: true,
minLength: 7
}
})

密码以小写形式存储,这就是为什么每次我匹配密码时它都显示为false的原因。

在数据库中存储密码时,我将其以小写字母存储,因此每次将用户输入的密码与数据库密码进行比较时,结果都为False。

因此,通过从用户模式的密码中删除lowercase: true,我的错误得到了解决。

最新更新