简体   繁体   中英

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.

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

compare returns a promise which is truthy

You wanted to use compareSync

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM