Home > Mobile >  How to access the request object before a Guards NestJS
How to access the request object before a Guards NestJS

Time:03-24

I have this route here:

@UseGuards(LocalAuthGuard)
  @Post('login')
  async login(
    @Request() req,
    @Body(new LoginUserValidationPipe()) body: LoginUserDto,
  ) {
    return this.authService.issueJWT(req.user);
  }

I am doing right now the error handling. This route expects an object with two properties: email and password. The scenario that I am thinking is when a user sends the request without the email property, having only the password. But it fails. I did use the class-validator package to handle the errors and validation, but the request never gets there. I think the Guards already pick up that something is wrong and throw an error, but I didn't want that. My local strategy is as follows:

export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'email',
    });
  }

  async validate(email: string, password: string): Promise<UserDto> {

    const user = await this.authService.validateUser(email, password);
    if (!user) {
      throw new NotFoundException();
    }
    return user;
  }
}

Does anyone know how can I access the request before the Guards? I tried creating another Guard and putting it before this one, but it didn't work.

CodePudding user response:

Guards are always ran before other enhancers as it is stated in the docs. The only way to run a guard before another guard is to put it at a higher priority (either at a handler level above [e.g. original guard is route handler level so new guard is at controller level]) or to put it before the guard in the @UseGuards(). The other option you have would be to run a middleware to validate your body here.

  • Related