Skip to content

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

7.8 KB
Raw Blame
/**
 * Basic Supabase-backed auth provider feeding the unified AuthContext.
 *
 * This is the portable provider used by the shared unified auth (e.g. the
 * portal in Supabase mode). It deliberately does NOT carry the editor saas
 * build's extras (pro status, profile pictures, teams) - those remain in the
 * editor's saas layer. It maps a Supabase session onto the provider-agnostic
 * AuthUser/AuthSession shapes and exposes the same useAuth() contract as the
 * Spring provider.
 */
import { useCallback, useEffect, useState, type ReactNode } from "react";
import type {
  Session as SbSession,
  User as SbUser,
} from "@supabase/supabase-js";
import { getSupabaseClient } from "@editor/auth/supabase/supabaseClient";
import { AuthContext } from "@editor/auth/context";
import { isAdminRole } from "@editor/auth/roles";
import { getApiBaseUrl } from "@editor/services/apiClientConfig";
import {
  defaultTranslate,
  type AuthContextValue,
  type AuthError,
  type AuthSession,
  type AuthUser,
  type AuthTranslate,
} from "@editor/auth/types";

function readRole(user: SbUser): string {
  const appRole = (user.app_metadata as { role?: unknown } | undefined)?.role;
  if (typeof appRole === "string") return appRole;
  return "USER";
}

function mapUser(user: SbUser): AuthUser {
  const metadata = user.user_metadata as
    | { full_name?: string; name?: string; username?: string }
    | undefined;
  return {
    id: user.id,
    email: user.email ?? "",
    username:
      metadata?.username ||
      metadata?.full_name ||
      metadata?.name ||
      user.email ||
      "",
    role: readRole(user),
    is_anonymous: user.is_anonymous,
    app_metadata: user.app_metadata,
  };
}

function mapSession(session: SbSession | null): AuthSession | null {
  if (!session) return null;
  return {
    user: mapUser(session.user),
    access_token: session.access_token,
    expires_in: session.expires_in,
    expires_at: session.expires_at ? session.expires_at * 1000 : undefined,
  };
}

function deriveDisplayName(
  user: AuthUser | null,
  translate: AuthTranslate,
): string | null {
  if (!user) return null;
  if (user.is_anonymous) return translate("auth.displayName.guest", "Guest");
  return user.username || user.email || null;
}

export interface SupabaseAuthProviderProps {
  children: ReactNode;
  translate?: AuthTranslate;
}

export function SupabaseAuthProvider({
  children,
  translate = defaultTranslate,
}: SupabaseAuthProviderProps) {
  const [session, setSession] = useState<AuthSession | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<AuthError | null>(null);

  const refreshSession = useCallback(async () => {
    const supabase = getSupabaseClient();
    if (!supabase) return;
    setLoading(true);
    const { data, error } = await supabase.auth.refreshSession();
    if (error) {
      setError({ message: error.message });
      setSession(null);
    } else {
      setSession(mapSession(data.session));
    }
    setLoading(false);
  }, []);

  const signOut = useCallback(async () => {
    const supabase = getSupabaseClient();
    setSession(null);
    if (!supabase) return;
    const { error } = await supabase.auth.signOut();
    if (error) setError({ message: error.message });
  }, []);

  useEffect(() => {
    const supabase = getSupabaseClient();
    if (!supabase) {
      // Supabase mode requested but not configured - settle into a signed-out
      // state instead of hanging on "loading".
      setLoading(false);
      return;
    }

    let mounted = true;
    supabase.auth
      .getSession()
      .then(({ data }) => {
        if (!mounted) return;
        setSession(mapSession(data.session));
      })
      .catch((e: unknown) => {
        if (mounted) setError({ message: String(e) });
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });

    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange((_event, newSession) => {
      if (!mounted) return;
      setSession(mapSession(newSession));
      setError(null);
    });

    return () => {
      mounted = false;
      subscription.unsubscribe();
    };
  }, []);

  // Enrich with backend truth: grant-based portal access and team leadership come from
  // /api/v1/auth/me, not Supabase claims. Portal/Processor access is active-team-dependent on the
  // backend, and a team switch made elsewhere doesn't change our session object - so besides the
  // initial load we re-validate whenever the tab regains focus, else a user whose access dropped
  // would keep seeing the Processor until a full reload. Best-effort; the isAdminRole fallback
  // below covers failures and anonymous sessions.
  useEffect(() => {
    const token = session?.access_token;
    const sessionUser = session?.user;
    if (!token || !sessionUser || sessionUser.is_anonymous) {
      return;
    }
    let cancelled = false;
    // Same API base the rest of the app uses: SaaS serves the frontend and the
    // API from different hosts, so a root-relative path never reaches /me.
    const apiBase = (getApiBaseUrl() || "").replace(/\/+$/, "");
    const meUrl = `${apiBase}/api/v1/auth/me`;
    const loadAccess = () => {
      void fetch(meUrl, {
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
        },
      })
        .then((res) => {
          // Must throw, not resolve null: swallowing a non-ok leaves
          // portalAccess undefined and hangs the portal gate on a spinner.
          if (!res.ok) throw new Error(`auth/me responded ${res.status}`);
          return res.json();
        })
        .then(
          (
            data: {
              user?: {
                portalAccess?: boolean;
                teamLead?: boolean;
                orgOwner?: boolean;
              };
            } | null,
          ) => {
            if (cancelled || !data?.user) return;
            setSession((prev) =>
              prev
                ? {
                    ...prev,
                    user: {
                      ...prev.user,
                      portalAccess: data.user?.portalAccess,
                      teamLead: data.user?.teamLead,
                      orgOwner: data.user?.orgOwner,
                    },
                  }
                : prev,
            );
          },
        )
        .catch(() => {
          // Backend unreachable or /me unsupported: resolve portalAccess to the role-based
          // fallback so gates awaiting it don't hang on a spinner. This deliberately ignores
          // grant-based access (a non-admin grant-holder is denied while /me is down) - grants
          // can't be known without /me, so we fail safe; a later focus refetch recovers it.
          if (cancelled) return;
          setSession((prev) =>
            prev && prev.user.portalAccess === undefined
              ? {
                  ...prev,
                  user: {
                    ...prev.user,
                    portalAccess: isAdminRole(prev.user.role),
                  },
                }
              : prev,
          );
        });
    };
    loadAccess();
    const onVisible = () => {
      if (document.visibilityState === "visible") loadAccess();
    };
    document.addEventListener("visibilitychange", onVisible);
    return () => {
      cancelled = true;
      document.removeEventListener("visibilitychange", onVisible);
    };
  }, [session?.access_token, session?.user?.id]);

  const user = session?.user ?? null;
  const value: AuthContextValue = {
    session,
    user,
    displayName: deriveDisplayName(user, translate),
    isAnonymous: user?.is_anonymous === true,
    isAdmin: isAdminRole(user?.role),
    portalAccess: user?.portalAccess ?? isAdminRole(user?.role),
    role: user?.role ?? null,
    loading,
    error,
    signOut,
    refreshSession,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}