简体   繁体   English

Bcrypt compare() 总是返回 false

[英]Bcrypt compare() always return false

I have used this code for comparison.我已使用此代码进行比较。

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
}

I always get an invalid credentials error from the below login function.我总是从下面的登录 function 中得到一个无效的凭据错误。 I have checked by logging the outputs.我已经通过记录输出进行了检查。 The problem lies with the compare password functionality.问题在于比较密码功能。

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 })

}

This might be helpful to someone,这可能对某人有帮助,

I got the same errror while working with postgresql, I replaced the hash password variable with hardcoded hash string and it worked.我在使用 postgresql 时遇到了同样的错误,我用硬编码的 hash 字符串替换了 hash 密码变量,它起作用了。 So I console logged the user password retrieved from the database and noticed that whitespace was included in the result, the number of whitespace included when summed up with length of the user password gives the exact length precision of the password column, so you can either trim the user.password or redefine your database so that it doesn't include whitespace when queried.所以我控制台记录了从数据库中检索到的用户密码,并注意到结果中包含空格,当与用户密码的长度相加时包含的空格数给出了密码列的确切长度精度,因此您可以修剪user.password 或重新定义您的数据库,使其在查询时不包含空格。

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

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