@nestjs/graphql#GqlExecutionContext TypeScript Examples

The following examples show how to use @nestjs/graphql#GqlExecutionContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: gql.auth-guard.ts    From svvs with MIT License 6 votes vote down vote up
/**
   * getRequest return ExecutionContext as GqlExecutionContext request
   *
   * @param context
   */
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context)

    return ctx.getContext().req
  }
Example #2
Source File: gqlUserRoles.decorator.ts    From amplication with Apache License 2.0 6 votes vote down vote up
UserRoles = createParamDecorator(
  (data: string, context: ExecutionContext) => {
    const ctx = GqlExecutionContext.create(context);
    const request = ctx.getContext<{ req: { user: any } }>().req;
    if (!request.user) {
      return null;
    }
    return data ? request.user[data] : request.user.roles;
  }
)
Example #3
Source File: userData.decorator.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
 * Access the user data from the request object i.e `req.user`.
 */
function userFactory(ctx: ExecutionContext): User {
  const contextType = ctx.getType();
  if (contextType === "http") {
    // do something that is only important in the context of regular HTTP requests (REST)
    const { user } = ctx.switchToHttp().getRequest();
    return user;
  } else if (contextType === "rpc") {
    // do something that is only important in the context of Microservice requests
    throw new Error("Rpc context is not implemented yet");
  } else if (contextType === "ws") {
    // do something that is only important in the context of Websockets requests
    throw new Error("Websockets context is not implemented yet");
  } else if (ctx.getType<GqlContextType>() === "graphql") {
    // do something that is only important in the context of GraphQL requests
    const gqlExecutionContext = GqlExecutionContext.create(ctx);
    return gqlExecutionContext.getContext().req.user;
  }
  throw new Error("Invalid context");
}
Example #4
Source File: roles.guard.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
canActivate(context: ExecutionContext): boolean {
    const ctx = GqlExecutionContext.create(context);

    const roles = this.reflector.get<string[]>('roles', ctx.getHandler());
    if (!roles) {
      return true;
    }

    const userRoles = ctx.getContext().req.user ? ctx.getContext().req.user.roles : []

    for (const role of roles) {
      if (!userRoles.includes(role)) {
        return false;
      }
    }

    return true;
  }
Example #5
Source File: gql-auth.guard.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
   * Returns whether the request is authorized to activate the handler
   */
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // Check context with AuthGuard
    if (!(await super.canActivate(context))) {
      return false;
    }

    const ctx = GqlExecutionContext.create(context);
    const req = this.getRequest(context);
    const currentUser = req.user;
    const handler = context.getHandler();

    const requestArgs = ctx.getArgByIndex(1);

    return (
      this.canActivateRoles(handler, currentUser) &&
      (await this.authorizeContext(handler, requestArgs, currentUser))
    );
  }
Example #6
Source File: inject-context.interceptor.ts    From amplication with Apache License 2.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler) {
    const handler = context.getHandler();
    const graphqlContext = GqlExecutionContext.create(context);
    const { req } = graphqlContext.getContext();
    const args = graphqlContext.getArgs();

    const params = this.getInjectContextValueParameters(handler);

    if (!params) {
      return next.handle();
    }

    const { parameterPath, parameterType } = params;

    const parameterValue = this.getInjectableContextValue(
      req.user,
      parameterType
    );

    set(args, parameterPath, parameterValue);

    return next.handle();
  }
Example #7
Source File: gql-auth-mock.ts    From amplication with Apache License 2.0 6 votes vote down vote up
mockGqlAuthGuardCanActivate = (user: object) => (
  executionContext: ExecutionContext
): boolean => {
  const gqlExecutionContext = GqlExecutionContext.create(executionContext);
  const gqlContext = gqlExecutionContext.getContext();
  // Set user for injectContextValue to work properly
  set(gqlContext, ['req', 'user'], user);
  return true;
}
Example #8
Source File: gql.auth.guard.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
getRequest(context: ExecutionContext) {
    if (context.getType<any>() === 'graphql') {
      const ctx = GqlExecutionContext.create(context);

      if (!ctx.getContext().cache) {
        ctx.getContext().cache = new ContextCache()
      }
      return ctx.getContext().req;
    }

    return context.switchToHttp().getRequest()
  }
Example #9
Source File: tracing-context.decorator.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
Tracing = createParamDecorator(
  (key: keyof TracingData, context: ExecutionContext) => {
    const contextType = context.getType<GqlContextType>();
    let tracingData: TracingData;
    if (contextType === 'graphql') {
      const ctx = GqlExecutionContext.create(context);
      tracingData = ctx.getContext<TracingObject>().tracing;
    }
    if (contextType === 'http') {
      const ctx = context.switchToHttp();
      tracingData = ctx.getRequest<TracingObject>().tracing;
    }
    if (contextType === 'rpc') {
      const ctx = context.switchToRpc();
      tracingData = ctx.getContext<TracingObject>().tracing;
    }
    return key ? tracingData && tracingData[key] : tracingData;
  },
)
Example #10
Source File: user.decorator.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
User = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const user = GqlExecutionContext.create(ctx).getContext().req.user

    if (!user) {
      return null
    }

    return user
  },
)
Example #11
Source File: ip.address.decorator.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
IpAddress = createParamDecorator((data: string, ctx: ExecutionContext) => {
  let req

  if (ctx.getType<string>() === 'graphql') {
    req = GqlExecutionContext.create(ctx).getContext().req
  } else {
    req = ctx.switchToHttp().getRequest()
  }

  if (req.clientIp) {
    return req.clientIp
  }

  return getClientIp(req)
})
Example #12
Source File: extract-request.ts    From nestjs-keycloak-admin with MIT License 5 votes vote down vote up
export function extractRequest(context: ExecutionContext): any {
  if (context.getType<GqlContextType>() === 'graphql') {
    const gqlContext = GqlExecutionContext.create(context)
    return gqlContext.getContext().req
  }
  return context.switchToHttp().getRequest()
}
Example #13
Source File: graphql.guard.ts    From knests with MIT License 5 votes vote down vote up
getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
Example #14
Source File: auth.guard.ts    From NextJS-NestJS-GraphQL-Starter with MIT License 5 votes vote down vote up
canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const { req } = ctx.getContext();

    return Boolean(req.user && Object.values(Roles).includes(req.user.role));
  }
Example #15
Source File: admin.guard.ts    From NextJS-NestJS-GraphQL-Starter with MIT License 5 votes vote down vote up
canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const { req } = ctx.getContext();

    return Boolean(req.user && req.user.role === Roles.ADMIN);
  }
Example #16
Source File: local.auth.guard.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
getRequest(context: ExecutionContext) {
    return GqlExecutionContext.create(context).getContext().req
  }
Example #17
Source File: environment.interceptor.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
        const ctx = GqlExecutionContext.create(context);
        const {environmentNameOrId} = ctx.getArgs();
        const environment = await this.systemProvider.getEnvironment(environmentNameOrId);
        ctx.getContext().environment = environment;

        return next.handle();
    }
Example #18
Source File: environment.guard.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
async canActivate(context: ExecutionContext): Promise<boolean> {
        const ctx = GqlExecutionContext.create(context);
        const {fieldName} = ctx.getInfo();
        const {environmentNameOrId} = ctx.getArgs();
        const environment = await this.systemProvider.getEnvironment(environmentNameOrId);

        return environment.supports(fieldName);
    }
Example #19
Source File: cats.guard.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
canActivate(context: ExecutionContext): boolean {
    const ctx = GqlExecutionContext.create(context);
    return true;
  }
Example #20
Source File: gql-auth.guard.ts    From amplication with Apache License 2.0 5 votes vote down vote up
// This method is required for the interface - do not delete it.
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
Example #21
Source File: user.decorator.ts    From amplication with Apache License 2.0 5 votes vote down vote up
export function getUser(executionContext: ExecutionContext): User {
  const gqlExecutionContext = GqlExecutionContext.create(executionContext);
  return gqlExecutionContext.getContext().req.user;
}
Example #22
Source File: gqlDefaultAuth.guard.ts    From amplication with Apache License 2.0 5 votes vote down vote up
// This method is required for the interface - do not delete it.
  getRequest(context: ExecutionContext): Request {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext<{ req: Request }>().req;
  }
Example #23
Source File: gqlAC.guard.ts    From amplication with Apache License 2.0 5 votes vote down vote up
async getUser(context: ExecutionContext): Promise<User> {
    const ctx = GqlExecutionContext.create(context);
    const request = ctx.getContext<{ req: { user: User } }>().req;
    return request.user;
  }
Example #24
Source File: gql-jwt-auth.guard.ts    From whispr with MIT License 5 votes vote down vote up
getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
Example #25
Source File: tracing.interceptor.ts    From nestjs-jaeger-tracing with MIT License 4 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const contextType = context.getType<GqlContextType>();
    const except = this.reflector.get<boolean>(
      EXCEPT_TRACING,
      context.getHandler(),
    );
    if (contextType === 'ws') {
      return next.handle();
    }
    if (except) {
      if (contextType === 'rpc') {
        const ctx = context.switchToRpc();
        const data = ctx.getData<TracingContext>();
        if (isTracingContext(data)) {
          context.getArgs()[0] = data.payload;
        }
      }
      return next.handle();
    }
    let parentSpanContext: SpanContext;
    const spanTags = new Map<string, unknown>();
    const spanLogs: Array<Record<string, unknown>> = [];
    const constructorRef = context.getClass().name;
    const handler = context.getHandler().name;
    const operation = [contextType, constructorRef, handler].join(':');
    const tracingData: TracingData = { operation };
    spanTags.set('operation', operation);
    spanTags.set(Tags.COMPONENT, contextType);
    if (contextType === 'graphql') {
      const ctx = GqlExecutionContext.create(context);
      ctx.getContext<TracingObject>().tracing = tracingData;
      const { path } = ctx.getInfo<GraphQLResolveInfo>();
      spanTags.set('graphql.name', `${path?.key}`);
      spanTags.set('graphql.type', `${path?.typename}`.toLowerCase());
    }
    if (contextType === 'http') {
      const ctx = context.switchToHttp();
      ctx.getRequest<TracingObject>().tracing = tracingData;
      const { statusCode } = ctx.getResponse<Response>();
      const { headers, method, path, ip, ips } = ctx.getRequest<Request>();
      spanTags.set(Tags.HTTP_URL, path);
      spanTags.set(Tags.HTTP_METHOD, `${method}`.toUpperCase());
      spanTags.set(Tags.PEER_HOST_IPV4, [ip, ...ips].join(', '));
      spanTags.set(Tags.HTTP_STATUS_CODE, statusCode);
      parentSpanContext = this.tracerProvider.extractHeaders(headers);
    }
    if (contextType === 'rpc') {
      const ctx = context.switchToRpc();
      const data = ctx.getData<TracingContext>();
      if (isTracingContext(data)) {
        const { payload, tracing } = data;
        context.getArgs()[0] = payload;
        tracingData.parent = tracing;
        parentSpanContext = this.tracerProvider.extractTracing(tracing);
      }
      ctx.getContext<TracingObject>().tracing = tracingData;
      if (typeof ctx.getContext().getPattern === 'function') {
        const pattern = ctx.getContext().getPattern();
        spanTags.set('rpc.pattern', pattern);
      }
      if (typeof ctx.getContext().getChannel === 'function') {
        const channel = ctx.getContext().getChannel();
        spanTags.set('rpc.channel', channel);
      }
      if (typeof ctx.getContext().getSubject === 'function') {
        const subject = ctx.getContext().getSubject();
        spanTags.set('rpc.subject', subject);
      }
      if (typeof ctx.getContext().getTopic === 'function') {
        const topic = ctx.getContext().getTopic();
        spanTags.set('rpc.topic', topic);
      }
      spanLogs.push({ payload: JSON.stringify(ctx.getData(), null, 2) });
    }
    return this.asyncContext.run(() => {
      const span = this.tracer.startSpan(operation, {
        childOf: parentSpanContext,
        tags: { kind: 'server' },
      });
      spanTags.forEach((value: string, key: string) => {
        span.setTag(key, value);
      });
      spanLogs.forEach((log) => {
        span.log(log);
      });
      tracingData.carrier = this.tracerProvider.getCarrier(span);
      this.asyncContext.set(TRACING_CARRIER_INFO, tracingData);
      return next.handle().pipe(
        tap(() => {
          span.finish();
        }),
        catchError((error: Error) => {
          span.setTag(Tags.ERROR, true);
          if (error instanceof HttpException) {
            const tag =
              contextType === 'http'
                ? Tags.HTTP_STATUS_CODE
                : 'error.status_code';
            span.setTag(tag, error.getStatus());
          }
          span.log({
            event: Tags.ERROR,
            'error.object': error,
            message: error.message,
            stack: error.stack,
          });
          span.finish();
          return throwError(error);
        }),
      );
    }) as Observable<unknown>;
  }