Skip to content
Advertisement

Bcrypt.compare always returns true

I am using NestJS and Passport to create a simple log in/registration form and I am using bcrypt to see if the password that has been hashed is matching the password that user provides in the login form, but it always returns true

    async validateUser(username: string, pass: string): Promise<any> {
        const user = await this.usersService.findOne(username);
        if(user && bcrypt.compare('pass', user.password)) {
            const { password, ...result } = user;
            console.log(pass, user.password)
            return result;
        }
        return null;
    }

In the code above, even if I set the argument as a string it will return true and go inside the if statement, which should be false.

Advertisement

Answer

As the compare function of the returns a promise, you need to await it. Try this:

async validateUser(username: string, pass: string): Promise<any> {
        const user = await this.usersService.findOne(username);
        if (!user) return null;
        const pwCheck = await bcrypt.compare('pass', user.password);
        if (!pwCheck) return null;
        const { password, ...result } = user;
        return result;
    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement