Bcryptcompare() 总是返回 false

问题描述 投票:0回答:2

我用这个代码进行比较。

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
}

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

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

}
javascript node.js express hash bcrypt
2个回答
0
投票

这可能对某人有帮助,

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


0
投票

检查以确保哈希值是第二个参数,并且提供的密码是第一个参数。

© www.soinside.com 2019 - 2024. All rights reserved.