【发布时间】:2022-01-22 16:38:29
【问题描述】:
我正在尝试使用我的凭据登录,但在从数据库加载后匹配密码时,如果密码仍然正确,它总是返回 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
}
})
密码以小写形式存储,这就是为什么每次我匹配我的密码时它都会显示错误。
【问题讨论】:
-
每次你散列密码时,由于随机盐,它会有所不同。这是设计使然。这就是为什么您不再对密码进行哈希处理,而是使用特殊的比较功能将明文密码与存储的哈希进行比较。
标签: node.js mongodb mongoose encryption bcrypt