繁体   English   中英

Bcrypt compare() 总是返回 false

[英]Bcrypt compare() always return false

我已使用此代码进行比较。

UserSchema.pre('save', async function() {
    const salt = await bcrypt.genSalt(10)
    this.password = await bcrypt.hash(this.password, salt)
})

UserSchema.methods.comparePassword = async function(candidatePassword) {
    const isMatch = await bcrypt.compare(candidatePassword, this.password)
    console.log(this.password);
    console.log(candidatePassword);
    return isMatch
}

我总是从下面的登录 function 中得到一个无效的凭据错误。 我已经通过记录输出进行了检查。 问题在于比较密码功能。

const login = async(req, res) => {
    const { email, password } = req.body

    if (!email || !password) {
        throw new CustomError.BadRequestError('Please provide email and password')
    }

    const user = await User.findOne({ email })

    if (!user) {
        throw new CustomError.UnauthenticatedError('Invalid Credentials')
    }

    const isPasswordCorrect = await user.comparePassword(password)

    if (!isPasswordCorrect) {
        throw new CustomError.UnauthenticatedError('Invalid Credentials')

    }

    if (!user.isVerified) {
        throw new CustomError.UnauthenticatedError('Please Verify Your Email ')
    }

    const tokenUSer = createTokenUser(user)
    attachCookiesToResponse({ res, user: tokenUSer })

    res.status(StatusCodes.OK).json({ user: tokenUSer })

}

这可能对某人有帮助,

我在使用 postgresql 时遇到了同样的错误,我用硬编码的 hash 字符串替换了 hash 密码变量,它起作用了。 所以我控制台记录了从数据库中检索到的用户密码,并注意到结果中包含空格,当与用户密码的长度相加时包含的空格数给出了密码列的确切长度精度,因此您可以修剪user.password 或重新定义您的数据库,使其在查询时不包含空格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM