I want to create RolesGuard for Graphql
I create Roles decorator like following
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
And I create GqlAuthGuard and RolesGuard like following
gql-gurad.ts
@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
getRequest(context: ExecutionContext){
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
}
role-guard.ts
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
...
}
}
but line const request = context.switchToHttp().getRequest();
returns undefined.
and i'm using two guards like following
@AuthGuard(GqlAuthGuard, RolesGuard)
@Mutation(...)
What did I miss??
I solved it myself.
const request = context.switchToHttp().getRequest();
const user = request.user;
to
const ctx = GqlExecutionContext.create(context);
const user = ctx.getContext().req.user;
i found it from nestjs discord channel.
https://discordapp.com/channels/520622812742811698/520649487924985885
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