nestjs-rbac icon indicating copy to clipboard operation
nestjs-rbac copied to clipboard

Graphql support

Open NikolayYakovenko opened this issue 3 years ago • 3 comments

Hi, @sergey-telpuk!

Do your rbac module support of graphql request? I want to add RBAcPermissions and @UseGuards(RBAcGuard) to graphql resolver. But I suppose that this code is not working with graphql request.

NikolayYakovenko avatar Feb 16 '22 11:02 NikolayYakovenko

@NikolayYakovenko Hi, I've never tested it for Graphql. Glad to see the issues with it.

sergey-telpuk avatar Feb 16 '22 15:02 sergey-telpuk

When we use RBAcPermissions and @UseGuards(RBAcGuard) in graphql resolver, we get an error:

ERROR: ExceptionsHandler TypeError: Cannot read properties of undefined (reading 'user')
    at RBAcGuard.canActivate (/node_modules/nestjs-rbac/src/guards/rbac.guard.ts:27:37)

The problem is here. As I know const request = context.switchToHttp().getRequest(); can be used only for REST.

To get request object in graphql we do like this:

import { GqlExecutionContext } from '@nestjs/graphql';

const request = GqlExecutionContext.create(context).getContext().req;

And depends on request type http or graphql, we can implement logic to get correct request object.

The full code would be following:

const contextType = context.getType();

if (contextType === 'http') {
  `return context.switchToHttp().getRequest();
} else if (contextType === 'graphql') {
  return GqlExecutionContext.create(context).getContext().req;
}

throw new Error('Unknown context type');

Here is an example in another module

NikolayYakovenko avatar Feb 16 '22 16:02 NikolayYakovenko

@NikolayYakovenko Looks like PR. I don't mind considering this logic, anyway I'll try it out in soon time, thanks.

sergey-telpuk avatar Feb 16 '22 20:02 sergey-telpuk