Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access the request object before a Guards NestJS

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading