Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specify guards execution order in documentation #1567

Closed
egormkn opened this issue Nov 22, 2020 · 2 comments
Closed

Specify guards execution order in documentation #1567

egormkn opened this issue Nov 22, 2020 · 2 comments

Comments

@egormkn
Copy link

egormkn commented Nov 22, 2020

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request (new chapter/page)
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

The documentation states that:

  • Middlewares are run sequentially in the order they are bound.
  • As with middleware, guards run in the order in which they are bound.

This can be understood as the guards for the route are executed from top to bottom, in the order they appear in the source code. However, as I see, guards are executed in the reverse order.

Minimal reproduction of the problem with instructions

import { CanActivate, Controller, ExecutionContext, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';

class SampleGuard implements CanActivate {
  constructor(private readonly name: string) {}

  canActivate(context: ExecutionContext): boolean {
    console.log(`Executing guard "${this.name}"`);
    return true;
  }
}

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  @UseGuards(new SampleGuard('first'))
  @UseGuards(new SampleGuard('second'))
  getHello(): string {
    return this.appService.getHello();
  }
}

Output:

Executing guard "second"
Executing guard "first"

Expected behavior

There are two ways for resolving this issue:

  1. Specify this order in the documentation as it is already specified for the @UseGuards(Guard1, Guard2) case.
  2. Change guard execution order so the guards are executed from top to bottom, as they appear in the source code. This option seems to be better from the user's point of view, because it will be easier to read the controller's source code, but it might break some existing code that expects reverse guards order.

Also, I would suggest introducing some kind of style guide for controller decorators' order (method => guards => interceptors => pipes => filters) and maintain this order in the documentation examples. Although, this is a subject for another issue.

What is the motivation / use case for changing the behavior?

I have created a NoAuth decorator that, as opposed to the Auth decorator, prevents authenticated users from accessing /auth/login, /auth/register and other authentication-related pages of MVC application.

import { applyDecorators, UseFilters, UseGuards } from '@nestjs/common';
import { ForbiddenExceptionFilter } from '../filters/forbidden-exception.filter';
import { NoAuthenticationGuard } from '../guards/no-authentication.guard';

export function NoAuth() {
  return applyDecorators(UseGuards(NoAuthenticationGuard), UseFilters(ForbiddenExceptionFilter));
}
import { ExecutionContext, Injectable, CanActivate } from '@nestjs/common';

@Injectable()
export class NoAuthenticationGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return !request.isAuthenticated();
  }
}
import { ExceptionFilter, Catch, ArgumentsHost, ForbiddenException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(ForbiddenException)
export class ForbiddenExceptionFilter implements ExceptionFilter<ForbiddenException> {
  catch(exception: ForbiddenException, host: ArgumentsHost) {
    const context = host.switchToHttp();
    const response = context.getResponse<Response>();
    response.redirect('/');
  }
}

I want to use it in the AuthController like that:

...
  @Get('google')
  @NoAuth()                   // Redirect if authenticated
  @UseGuards(GoogleAuthGuard) // Else start the OAuth authentication process
  googleLogin(): void {}

  @Get('google/callback')
  @NoAuth()                   // Redirect if authenticated
  @UseGuards(GoogleAuthGuard) // Else authenticate with OAuth
  googleCallback(@User() user: UserEntity) {
    return this.authService.login(user);
  }
...

Now I need to change the order of these decorators to make it work as intended.

Environment


- NestJS version: 7.5.1
- Node version: 14.15.1  
- Platform: Linux 
@jmcdo29
Copy link
Member

jmcdo29 commented Nov 22, 2020

This can be understood as the guards for the route are executed from top to bottom, in the order they appear in the source code. However, as I see, guards are executed in the reverse order.

This seems logical at first, but it's something fundamental about how decorators work in Typescript. They resolve in the opposite order that they are bound top-to-bottom, hence why above you get second then first in your logs.

Generally, it's actually a bad idea to use the same decorator multiple times due to overriding metadata, but the way Nest implemented the setting of meteadata means that you are able to call @UseGuards() several times with the metadata still being persisted.

Of your two solutions, documenting the behavior is probably going to be the only one possible, again, because of how decorators work in Typescript.

@eyalyoli
Copy link

UseGuards(...) accepts multiple guards to check by order - no need for nesting decorators

@nestjs nestjs locked and limited conversation to collaborators Jul 20, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants