import { CanActivate , ExecutionContext , Injectable } from '@nestjs/common' ; import { Reflector } from '@nestjs/core' ; import { GqlContextType , GqlExecutionContext } from '@nestjs/graphql' ; import type { Request } from 'express' ; @ Injectable ( ) export class RolesGuard implements CanActivate { constructor ( private reflector ) { } public canActivate ( context ) { const roles = this . reflector . getAllAndOverride < string [ ] > ( 'roles' , [ context . getHandler ( ) , context . getClass ( ) , ] ) ; if ( ! roles ) { return true ; } let request ; if ( context . getType < GqlContextType > ( ) === 'graphql' ) { const ctx = GqlExecutionContext . create ( context ) . getContext ( ) ; request = < Request > ctx . req ; } else { request = context . switchToHttp ( ) . getRequest < Request > ( ) ; } const { user } = request ; if ( ! user ) { return false ; } return user . roles . some ( ( role ) => roles . includes ( role ) ) ; } }