Skip to content

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

19.6 KB
Raw Blame
import {
  createContext,
  useContext,
  useEffect,
  useRef,
  useState,
  ReactNode,
  useCallback,
} from "react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { supabase } from "@editor/auth/supabase";
import type {
  Session,
  User as SupabaseUser,
  AuthError,
} from "@supabase/supabase-js";
import { synchronizeUserUpgrade } from "@editor/services/userService";
import {
  syncOAuthAvatar,
  getProfilePictureMetadata,
  getProviderAvatarUrl,
  type ProfilePictureMetadata,
} from "@editor/services/avatarSyncService";
import {
  resumeWorkbenchSession,
  suspendWorkbenchSession,
} from "@editor/services/workbenchSession";

// Extend Supabase User to include optional username for compatibility
export type User = SupabaseUser & { username?: string };

/**
 * Derive a display name from the Supabase user. Prefers the OAuth-provided
 * full_name / name, then the email. Anonymous users get the localised
 * "Guest" placeholder (SaaS's chosen label for guest sessions); returns
 * null only when there is no user object at all so consumers can pick
 * their own fallback.
 *
 * Exported for unit testing.
 */
export function deriveDisplayName(
  user: User | null | undefined,
  t: TFunction,
): string | null {
  if (!user) return null;
  if (user.is_anonymous) return t("auth.displayName.guest", "Guest");
  const metadata = user.user_metadata as
    | { full_name?: string; name?: string }
    | undefined;
  return (
    user.username || metadata?.full_name || metadata?.name || user.email || null
  );
}

interface AuthContextType {
  session: Session | null;
  user: User | null;
  /**
   * Human-readable name to show in the UI for the current session.
   * - A real identity (full_name / name / email) when the user is signed in.
   * - The localised "Guest" placeholder for anonymous (Supabase
   *   `is_anonymous`) sessions - SaaS's chosen label, see deriveDisplayName.
   * - null only when there is no user object at all (signed-out), so
   *   consumers can fall back to whatever makes sense.
   */
  displayName: string | null;
  /** Whether the current session is an anonymous (Supabase `is_anonymous`) guest. */
  isAnonymous: boolean;
  loading: boolean;
  error: AuthError | null;
  isPro: boolean | null;
  profilePictureUrl: string | null;
  /** Pending until this user's picture lookup resolves, including a missing picture. */
  profilePictureLoading: boolean;
  profilePictureMetadata: ProfilePictureMetadata | null;
  signOut: () => Promise<void>;
  refreshSession: () => Promise<void>;
  refreshProStatus: () => Promise<void>;
  refreshProfilePicture: () => Promise<void>;
  refreshProfilePictureMetadata: () => Promise<void>;
  /**
   * Session-level permission flags (see the core auth seam). Supabase
   * sessions don't carry them — consumers treat undefined as "not granted"
   * and fall back to app-config gates.
   */
  isAdmin?: boolean;
  portalAccess?: boolean;
}

const AuthContext = createContext<AuthContextType>({
  session: null,
  user: null,
  displayName: null,
  isAnonymous: false,
  loading: true,
  error: null,
  isPro: null,
  profilePictureUrl: null,
  profilePictureLoading: true,
  profilePictureMetadata: null,
  signOut: async () => {},
  refreshSession: async () => {},
  refreshProStatus: async () => {},
  refreshProfilePicture: async () => {},
  refreshProfilePictureMetadata: async () => {},
});

export function AuthProvider({ children }: { children: ReactNode }) {
  const [session, setSession] = useState<Session | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<AuthError | null>(null);
  const [isPro, setIsPro] = useState<boolean | null>(null);
  const [profilePictureUrl, setProfilePictureUrl] = useState<string | null>(
    null,
  );
  const [profilePictureResolvedFor, setProfilePictureResolvedFor] = useState<
    string | null
  >(null);
  const [profilePictureMetadata, setProfilePictureMetadata] =
    useState<ProfilePictureMetadata | null>(null);
  const sessionRef = useRef<Session | null>(null);
  const profilePictureRequest = useRef(0);

  const updateSession = useCallback((next: Session | null) => {
    const previousUser = sessionRef.current?.user;
    if (previousUser?.id !== next?.user.id) {
      profilePictureRequest.current += 1;
      setProfilePictureUrl(null);
      setProfilePictureResolvedFor(null);
    }
    sessionRef.current = next;
    setSession(next);
  }, []);

  const fetchProStatus = useCallback(
    async (sessionToUse?: Session | null) => {
      const currentSession = sessionToUse ?? session;

      if (!currentSession?.user) {
        console.debug(
          "[Auth Debug] No user session, skipping pro status fetch",
        );
        setIsPro(null);
        return;
      }

      try {
        console.debug(
          "[Auth Debug] Fetching pro status for user:",
          currentSession.user.id,
        );
        const { data: proStatus, error } = await supabase.rpc("is_pro");

        if (error) {
          console.error("[Auth Debug] Error checking Pro status:", error);
          setIsPro(false); // Default to false if there's an error
        } else {
          const isProUser = Boolean(proStatus);
          setIsPro(isProUser);
          console.debug("[Auth Debug] Pro status fetched:", isProUser);
        }
      } catch (error: unknown) {
        console.debug("[Auth Debug] Failed to fetch pro status:", error);
        setIsPro(false); // Default to false if there's an error
      }
    },
    [session],
  );

  const refreshProStatus = useCallback(async () => {
    await fetchProStatus();
  }, [fetchProStatus]);

  // Provider photo as interim fallback when the bucket copy is missing —
  // skipped when the user explicitly chose upload/removal (source "upload").
  const providerAvatarFallback = useCallback(
    async (user: SupabaseUser): Promise<string | null> => {
      try {
        const metadata = await getProfilePictureMetadata(user.id);
        if (metadata?.source === "upload") return null;
        return getProviderAvatarUrl(user);
      } catch {
        return getProviderAvatarUrl(user);
      }
    },
    [],
  );

  const fetchProfilePicture = useCallback(
    async (sessionToUse = sessionRef.current, syncProviderAvatar = false) => {
      const currentSession = sessionToUse;
      if (currentSession?.user.id !== sessionRef.current?.user.id) return;
      // Own the whole sync/read chain so an earlier upload cannot start a newer lookup.
      const request = ++profilePictureRequest.current;

      if (!currentSession?.user) {
        console.debug(
          "[Auth Debug] No user session, skipping profile picture fetch",
        );
        setProfilePictureUrl(null);
        setProfilePictureResolvedFor(null);
        return;
      }

      if (syncProviderAvatar) {
        await syncOAuthAvatar(currentSession.user).catch((err) => {
          console.debug("[Auth Debug] Failed to sync OAuth avatar:", err);
        });
        if (request !== profilePictureRequest.current) return;
      }

      let pictureUrl: string | null;
      try {
        const PROFILE_BUCKET = "profile-pictures";
        const profilePath = `${currentSession.user.id}/avatar`;

        console.debug(
          "[Auth Debug] Fetching profile picture for user:",
          currentSession.user.id,
        );
        const { data, error } = await supabase.storage
          .from(PROFILE_BUCKET)
          .createSignedUrl(profilePath, 60 * 60);

        if (error) {
          // Profile picture not found is expected for users without uploads
          console.debug(
            "[Auth Debug] Profile picture not available:",
            error.message,
          );
          pictureUrl = await providerAvatarFallback(currentSession.user);
        } else {
          pictureUrl = data.signedUrl;
          console.debug(
            "[Auth Debug] Profile picture URL fetched successfully",
          );
        }
      } catch (error: unknown) {
        console.debug("[Auth Debug] Failed to fetch profile picture:", error);
        pictureUrl = await providerAvatarFallback(currentSession.user);
      }
      if (request === profilePictureRequest.current) {
        setProfilePictureUrl(pictureUrl);
        setProfilePictureResolvedFor(currentSession.user.id);
      }
    },
    [providerAvatarFallback],
  );

  const refreshProfilePicture = useCallback(async () => {
    await fetchProfilePicture();
  }, [fetchProfilePicture]);

  const fetchProfilePictureMetadata = useCallback(
    async (sessionToUse?: Session | null) => {
      const currentSession = sessionToUse ?? session;

      if (!currentSession?.user) {
        console.debug(
          "[Auth Debug] No user session, skipping profile picture metadata fetch",
        );
        setProfilePictureMetadata(null);
        return;
      }

      try {
        console.debug(
          "[Auth Debug] Fetching profile picture metadata for user:",
          currentSession.user.id,
        );
        const metadata = await getProfilePictureMetadata(
          currentSession.user.id,
        );
        setProfilePictureMetadata(metadata);
        console.debug(
          "[Auth Debug] Profile picture metadata fetched:",
          metadata,
        );
      } catch (error: unknown) {
        console.debug(
          "[Auth Debug] Failed to fetch profile picture metadata:",
          error,
        );
        setProfilePictureMetadata(null);
      }
    },
    [session],
  );

  const refreshProfilePictureMetadata = useCallback(async () => {
    await fetchProfilePictureMetadata();
  }, [fetchProfilePictureMetadata]);

  // Refs, not state: the auth effect below has an empty dep array.
  const loadedForRef = useRef<string | null>(null);
  const inFlightRef = useRef<{ key: string; promise: Promise<void> } | null>(
    null,
  );

  /**
   * Sole owner of the per-user data fetching: mount-time init and every auth
   * event route through here. Idempotent per identity, since Supabase re-fires
   * SIGNED_IN and TOKEN_REFRESHED on token refresh and tab wakeups; pass
   * `force` for a genuine reload. The returned promise excludes the profile
   * picture, so awaiting it never blocks on an image download.
   */
  const loadUserData = useCallback(
    (
      sessionToLoad: Session | null,
      opts?: { force?: boolean },
    ): Promise<void> => {
      const user = sessionToLoad?.user;
      if (!user) {
        loadedForRef.current = null;
        return Promise.resolve();
      }

      // Not the access token, which changes every refresh. The anonymous flag
      // matters: a guest upgrade keeps the same id and must still refetch.
      const key = `${user.id}:${Boolean(user.is_anonymous)}`;
      if (!opts?.force && loadedForRef.current === key)
        return Promise.resolve();

      // The second of a concurrent init/SIGNED_IN pair adopts this promise so it
      // still awaits the load. A forced reload must not: the guest upgrade
      // would be silently dropped.
      if (!opts?.force && inFlightRef.current?.key === key)
        return inFlightRef.current.promise;

      const run = (async () => {
        // Off the awaited path: a first login re-uploads the provider avatar.
        // The signed-URL read chains behind it because reading first 404s and
        // silently falls back to the provider photo.
        void fetchProfilePicture(sessionToLoad, true).catch((err) => {
          console.debug("[Auth Debug] Failed to fetch profile picture:", err);
        });

        await Promise.all([
          fetchProStatus(sessionToLoad),
          fetchProfilePictureMetadata(sessionToLoad),
        ]);
        // Only on success: set up front, a concurrent caller short-circuits on
        // it and returns to a still-empty state. Also lets a failure retry.
        loadedForRef.current = key;
      })()
        .catch((err) => {
          console.debug("[Auth Debug] Failed to load user data:", err);
        })
        .finally(() => {
          // Only clear our own entry; a newer load may have superseded us.
          if (inFlightRef.current?.promise === run) inFlightRef.current = null;
        });

      inFlightRef.current = { key, promise: run };
      return run;
    },
    [fetchProStatus, fetchProfilePictureMetadata, fetchProfilePicture],
  );

  const refreshSession = async () => {
    try {
      setLoading(true);
      setError(null);
      const { data, error } = await supabase.auth.refreshSession();

      if (error) {
        console.error("[Auth Debug] Session refresh error:", error);
        setError(error);
        updateSession(null);
      } else {
        console.debug("[Auth Debug] Session refreshed successfully");
        updateSession(data.session);
      }
    } catch (err) {
      console.error(
        "[Auth Debug] Unexpected error during session refresh:",
        err,
      );
      setError(err as AuthError);
    } finally {
      setLoading(false);
    }
  };

  const signOut = async () => {
    try {
      setError(null);
      // Signing out is deliberate, unlike an identity check that merely failed: drop the
      // workbench record here and stop recording, so the teardown that follows cannot
      // write it back for whoever signs in next.
      suspendWorkbenchSession();

      const { error } = await supabase.auth.signOut();

      if (error) {
        console.error("[Auth Debug] Sign out error:", error);
        setError(error);
        // The sign-out did not happen and the session stands, so keep recording:
        // otherwise a still-signed-in user silently stops persisting their workbench.
        resumeWorkbenchSession();
      } else {
        console.debug("[Auth Debug] Signed out successfully");
        updateSession(null);
      }
    } catch (err) {
      console.error("[Auth Debug] Unexpected error during sign out:", err);
      setError(err as AuthError);
      resumeWorkbenchSession();
    }
  };

  useEffect(() => {
    let mounted = true;

    // Load current session on first mount
    const initializeAuth = async () => {
      try {
        console.debug("[Auth Debug] Initializing auth...");
        const { data, error } = await supabase.auth.getSession();

        if (!mounted) return;

        if (error) {
          console.error("[Auth Debug] Initial session error:", error);
          setError(error);
        } else {
          console.debug("[Auth Debug] Initial session loaded:", {
            hasSession: !!data.session,
            userId: data.session?.user?.id,
            email: data.session?.user?.email,
          });
          updateSession(data.session);

          // Awaited so the spinner does not clear before pro status is known.
          await loadUserData(data.session);
        }
      } catch (err) {
        console.error(
          "[Auth Debug] Unexpected error during auth initialization:",
          err,
        );
        if (mounted) {
          setError(err as AuthError);
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    };

    initializeAuth();

    // Subscribe to auth state changes
    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange(async (event, newSession) => {
      if (!mounted) return;

      console.debug("[Auth Debug] Auth state change:", {
        event,
        hasSession: !!newSession,
        userId: newSession?.user?.id,
        email: newSession?.user?.email,
        timestamp: new Date().toISOString(),
      });

      // Don't run supabase calls inside this callback; schedule them
      setTimeout(() => {
        if (mounted) {
          updateSession(newSession);
          setError(null);

          // Additional handling for specific events
          if (event === "SIGNED_OUT") {
            console.debug("[Auth Debug] User signed out, clearing session");
            // Clear pro status, profile picture, and metadata on sign out
            setIsPro(null);
            setProfilePictureUrl(null);
            setProfilePictureResolvedFor(null);
            setProfilePictureMetadata(null);
            loadedForRef.current = null;
          } else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
            console.debug("[Auth Debug] Signed in or token refreshed");
            // Deliberately does not touch `loading`: Supabase also fires
            // SIGNED_IN on tab wakeups, and gating the UI on it would unmount
            // Landing -> HomePage on every tab switch. Pinned by a test.
            void loadUserData(newSession);
          } else if (event === "USER_UPDATED") {
            console.debug("[Auth Debug] User updated");

            // Check if this is a pending OAuth upgrade completion
            const pendingUpgrade = sessionStorage.getItem("pendingUpgrade");
            const upgradeProvider = sessionStorage.getItem("upgradeProvider");

            if (
              pendingUpgrade &&
              newSession?.user &&
              newSession.user.is_anonymous === false
            ) {
              console.debug(
                "[Auth Debug] Processing pending OAuth upgrade:",
                upgradeProvider,
              );

              // Clear the flags first to prevent loops
              sessionStorage.removeItem("pendingUpgrade");
              sessionStorage.removeItem("upgradeProvider");

              // Synchronize with backend
              synchronizeUserUpgrade(upgradeProvider || undefined)
                .then(() => {
                  console.debug(
                    "[Auth Debug] User upgrade synchronized successfully",
                  );

                  // Forced: same user id, so the guest's data must be replaced.
                  return loadUserData(newSession, { force: true });
                })
                .then(() => {
                  console.debug(
                    "[Auth Debug] User data refreshed after upgrade",
                  );
                })
                .catch((err) => {
                  console.error(
                    "[Auth Debug] Failed to synchronize user upgrade:",
                    err,
                  );
                });
            }
          }
        }
      }, 0);
    });

    return () => {
      mounted = false;
      profilePictureRequest.current += 1;
      subscription.unsubscribe();
    };
    // Empty and load-bearing: must subscribe once. The closures are recreated
    // when `session` changes, so listing deps would re-subscribe on every auth
    // event; every call above passes its session explicitly instead. No lint
    // rule enforces this, so do not "fix" these deps.
  }, []);

  const { t } = useTranslation();
  const user = session?.user ?? null;
  const value: AuthContextType = {
    session,
    user,
    displayName: deriveDisplayName(user, t),
    isAnonymous: Boolean(user?.is_anonymous),
    loading,
    error,
    isPro,
    profilePictureUrl,
    profilePictureLoading: Boolean(
      user && profilePictureResolvedFor !== user.id,
    ),
    profilePictureMetadata,
    signOut,
    refreshSession,
    refreshProStatus,
    refreshProfilePicture,
    refreshProfilePictureMetadata,
  };

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

export function useAuth() {
  const context = useContext(AuthContext);

  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }

  return context;
}

// Debug hook to expose auth state for debugging
export function useAuthDebug() {
  const auth = useAuth();

  useEffect(() => {
    console.debug("[Auth Debug] Current auth state:", {
      hasSession: !!auth.session,
      hasUser: !!auth.user,
      loading: auth.loading,
      hasError: !!auth.error,
      userId: auth.user?.id,
      email: auth.user?.email,
      provider: auth.user?.app_metadata?.provider,
    });
  }, [auth.session, auth.user, auth.loading, auth.error]);

  return auth;
}