Home > Blockchain >  Bcrypt.compare always returns true
Bcrypt.compare always returns true

Time:10-09

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.

CodePudding user response:

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

CodePudding user response:

compare returns a promise which is truthy

You wanted to use compareSync

CodePudding user response:

As bcrypt.compare always returns a promise that's why it makes the condition satisfy as true. So, if you want to get response from bcrypt.compare you have to use await or.then block. So you can modify your code like this -

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

  return null;
}
  • Related