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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With