簡體   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