Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

1.6 KB
Raw Blame
import { useMemo } from "react";
import { t } from "ttag";

import type { SdkEntityToken } from "embedding-sdk-bundle/types";
import { extractResourceIdFromJwtToken, isJWT } from "metabase/utils/jwt";

export const useExtractResourceIdFromJwtToken = <TEntityId>({
  isGuestEmbed,
  resourceId,
  token,
}: {
  isGuestEmbed: boolean;
  resourceId: TEntityId | undefined;
  token: SdkEntityToken | undefined;
}): {
  resourceId: TEntityId | number | null;
  token: SdkEntityToken | null;
  tokenError?: string;
} => {
  return useMemo(() => {
    if (isJWT(resourceId)) {
      return {
        resourceId: null,
        token: null,
        tokenError: t`JWT tokens cannot be passed as id. Use the token prop instead.`,
      };
    }

    if (isGuestEmbed && resourceId) {
      return {
        resourceId: null,
        token: null,
        tokenError: t`A valid JWT token is required to be passed in guest embeds mode.`,
      };
    }

    if (token) {
      if (!isGuestEmbed) {
        return {
          resourceId: null,
          token: null,
          tokenError: t`Passing a token is only allowed for guest embeds mode.`,
        };
      }

      if (!isJWT(token)) {
        return {
          resourceId: null,
          token: null,
          tokenError: t`Passed token is not a valid JWT token.`,
        };
      }

      return { resourceId: extractResourceIdFromJwtToken(token), token };
    }

    if (resourceId) {
      return {
        resourceId,
        token: null,
      };
    }

    return {
      resourceId: null,
      token: null,
    };
  }, [resourceId, isGuestEmbed, token]);
};