【问题标题】:Hash Password does not match while loading from DB从数据库加载时哈希密码不匹配
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2013-05-19
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多