简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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