Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 417
Agnibha Avatar asked Nov 05 '19 15:11

Agnibha


2 Answers

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.

like image 184
Jay McDoniel Avatar answered Sep 19 '22 10:09

Jay McDoniel


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

like image 27
Thanh Le Hai Hoang Avatar answered Sep 18 '22 10:09

Thanh Le Hai Hoang