How to authenticate multiple entities using passport local strategies in nestJs?

735 views Asked by At

I have two different entities: company and users both must authenticate with email and password. I have set 2 different classes extending passport strategy as follows:

@Injectable()
export class LocalStrategyCompany extends PassportStrategy(Strategy) {
  constructor(private companyAuthenticationService: CompanyAuthenticationService) {
    super({
      usernameField: 'email'
    });
  }
  async validate(email: string, password: string): Promise<Company> {
    const company = this.companyAuthenticationService.getAuthenticatedCompany(email, password);
    if (!company) {
      throw new UnauthorizedException();
    }
    return company;
  }
  }

and local authenticaion guard class:

@Injectable()
export class LocalAuthenticationGuard extends AuthGuard('local') {}

and this login method in the auth controller:

@HttpCode(200)
  @UseGuards(LocalAuthenticationGuard)
  @Post('log-in')
  async logIn(@Req() request: RequestWithUser) {
    const {user} = request;
    const cookie = this.authenticationService.getCookieWithJwtToken(user.id);
    request.res.setHeader('Set-Cookie', cookie);
    return user;
  }

I have created the same in a CompanyAuthentication module but when i try to login with company i get wrong credentials error. Can you please help? btw I'm following this tutorial : https://wanago.io/2020/05/25/api-nestjs-authenticating-users-bcrypt-passport-jwt-cookies/

1

There are 1 answers

1
Micael Levi On

I think that this.companyAuthenticationService.getAuthenticatedCompany returns a Promise thus you need to use await keyword.

  const company = await this.companyAuthenticationService.getAuthenticatedCompany(email, password);