@graphql-mesh/plugin-jwt-auth
Version: 
62 lines (59 loc) • 2.25 kB
JavaScript
import { useJWT as useJWT$1 } from '@graphql-yoga/plugin-jwt';
export { createInlineSigningKeyProvider, createRemoteJwksSigningKeyProvider, extractFromConnectionParams, extractFromCookie, extractFromHeader } from '@graphql-yoga/plugin-jwt';
function useForwardedJWT(config) {
  const extensionsJwtFieldName = config.extensionsFieldName ?? "jwt";
  const extendContextFieldName = config.extendContextFieldName ?? "jwt";
  return {
    onContextBuilding({ context, extendContext }) {
      if (context.params.extensions?.[extensionsJwtFieldName]) {
        const jwt = context.params.extensions[extensionsJwtFieldName];
        extendContext({
          [extendContextFieldName]: jwt
        });
      }
    }
  };
}
function useJWT(options) {
  const forwardPayload = options?.forward?.payload ?? true;
  const forwardToken = options?.forward?.token ?? false;
  const shouldForward = forwardPayload || forwardToken;
  const fieldName = options?.forward?.extensionsFieldName ?? "jwt";
  return {
    onPluginInit({ addPlugin }) {
      const jwtPlugin = useJWT$1(options);
      addPlugin(
        // @ts-expect-error fix useYogaJWT typings to inherit the context
        jwtPlugin
      );
    },
    // When a subgraph is about to be executed, we check if the initial request has a JWT token
    // that needs to be passed. At the moment, only GraphQL subgraphs will have the option to forward tokens/payload.
    // The JWT info will be passed to the subgraph execution request.
    onSubgraphExecute({
      executionRequest,
      subgraphName,
      setExecutionRequest,
      logger
    }) {
      if (shouldForward && executionRequest.context?.jwt) {
        const jwtData = {
          payload: forwardPayload ? executionRequest.context.jwt.payload : void 0,
          token: forwardToken ? executionRequest.context.jwt.token : void 0
        };
        logger?.debug(
          `Forwarding JWT payload to subgraph ${subgraphName}, payload: `,
          jwtData.payload
        );
        setExecutionRequest({
          ...executionRequest,
          extensions: {
            ...executionRequest.extensions,
            [fieldName]: jwtData
          }
        });
      }
    }
  };
}
export { useJWT as default, useForwardedJWT, useJWT };