Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

1.6 KB
Raw Blame
import { type ReactNode } from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { RequirePortalAccess } from "@editor/auth";
import { Spinner } from "@editor/ui";
import { EDITOR_URL } from "@processor/auth/editorUrl";

// Stable module-level ref; RequirePortalAccess calls it from an effect.
function redirectToEditor(): void {
  window.location.href = EDITOR_URL;
}

function FullScreenMessage({ children }: { children: ReactNode }) {
  return (
    <div
      style={{
        minHeight: "100dvh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        gap: "0.75rem",
        color: "var(--c-text-subtle)",
      }}
    >
      {children}
    </div>
  );
}

/** Gates the portal: login when signed out, redirect to the editor without portal access. */
export function AuthGate({ children }: { children: ReactNode }) {
  const { t } = useTranslation();
  const location = useLocation();
  const returnTo = encodeURIComponent(
    location.pathname + location.search + location.hash,
  );
  return (
    <RequirePortalAccess
      fallback={<Navigate to={`/login?from=${returnTo}`} replace />}
      onForbidden={redirectToEditor}
      loading={
        <FullScreenMessage>
          <Spinner size="lg" label={t("portal.auth.loading", "Loading")} />
        </FullScreenMessage>
      }
      forbidden={
        <FullScreenMessage>
          {t("portal.auth.redirectingToEditor", "Redirecting to the editor...")}
        </FullScreenMessage>
      }
    >
      {children}
    </RequirePortalAccess>
  );
}