简体   繁体   中英

In NestJS is there any way to pass data from Guards to the controller?

So I am currently using NestJS extensively in my organization. And for authentication purposes we are using our own guards. So my question is that can anyone please guide me if there any way to pass data from guard to the controller, other than response.locals of expressjs? This is creating an hard dependency on the framework and I don't want that at this moment.

TIA.

The only ways possible to pass data from a Guard to a Controller is to either attach the data to a field on the request or to use some sort of metadata reflection, which may become more challenging than it is worth.

In your guard you could have a canActivate function like

canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
  const req = context.switchToHttp().getRequest();
  if (/* some logic with req */) {
    req.myData = 'some custom value';
  }
  return true;
}

And in your controller you could then pull req.myData and get the some custom value string back.

Instead of using the Guard, you can create your custom decorator to get the data:

export const Authorization = createParamDecorator((_, request: any) => {
  const { authorization: accessToken } = request.headers;
  try {
    const decoded = jwt.verify(accessToken, process.env.JWT_HASH);
    return pick(decoded, 'userId');
  } catch (ex) {
    throw new InvalidToken();
  }
});

export interface AuthUser {
  userId: string;
}

And pass to your controller like this:

  @Post()
  createFeedback(
    @Body() body: FeedbackBody,
    @Authorization() user: AuthUser,
  ): Promise<Feedback> {
    body.userId = user.userId;
    return this.feedbackService.feedback(body, user);
  }

This can act as a guard because when your token is invalid, it will throw an exception

as other guys said you can pass data on the request object on the guard but receiving them through the @Req decorator is not fancy, especially if you don't have any other use for the request object. You can create a custom decorator that will retrieve the data you want and inject them into any controller

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