dcodeIO / bcrypt.js

Optimized bcrypt in plain JavaScript with zero dependencies.
Other
3.47k stars 264 forks source link

Bcrypt compare method is not returning true when hash password is stored in the database. #131

Closed Irtiza751 closed 2 years ago

Irtiza751 commented 2 years ago
userSchema.statics.findByCredentials = async (email, password) => {
    const user = await User.findOne({ email })

    if (!user) {
        throw new Error('no user found!')
    }

    const isMatch = await bcrypt.compare(password, user.password)

    if (!isMatch) {
        throw new Error('invalid credentials!')
    }

    return user
}

The above code is matching the hash password that is stored in the database with a plain text password but it always returns false. so I tried this & it's working, could anyone explain to me; why this code is working & the above one is not working?

const bcrypt = require('bcryptjs')
const encription = async () => {
const password = 'abc1234';
console.log('plain password: ', password);

const hashPass = await bcrypt.hash(password, 8);
console.log(`hash password: ${hashPass}`);

const isValidPass = await bcrypt.compare(password, hashPass);
console.log(`is valid: ${isValidPass}`);
}

encription();
berazo29 commented 2 years ago

I did a minimal example on my computer and it works fine. Do you mean that 'isMatch' returns false?

Irtiza751 commented 2 years ago

Yeah, it is returning false for some reason I don't know why, but then I recreated the project from scratch and install all dependencies through yarn instead of npm and it started working.

Anyways thank you so much for replying, it feels really good that the community around JavaScript is so responsive & helpful.