Skip to content

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

8.9 KB
Raw Blame
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { resolveLandingPath } from "@editor/utils/loginLanding";
import { supabase } from "@editor/auth/supabase";
import { Button } from "@editor/ui/Button";
import { withBasePath } from "@editor/constants/app";
import { readPendingConnect } from "@editor/routes/pendingConnect";
import { isSafePostLoginRedirect } from "@editor/services/postLoginRedirect";
import { takePendingDestination } from "@editor/services/pendingDestination";
import { AuthShell } from "@editor/auth/ui/AuthShell";
import ErrorMessage from "@editor/auth/ui/ErrorMessage";
import { Spinner } from "@editor/ui/Spinner";
import "@editor/auth/ui/auth.css";
import loginHeader from "@editor/assets/brand/modern-logo/LoginLightModeHeader.svg";

interface CallbackState {
  status: "processing" | "success" | "error";
  message: string;
  details?: Record<string, unknown>;
}

export default function AuthCallback() {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [state, setState] = useState<CallbackState>({
    status: "processing",
    message: t("auth.callback.processing", "Processing authentication..."),
  });

  useEffect(() => {
    const handleCallback = async () => {
      try {
        const url = new URL(window.location.href);
        const code = url.searchParams.get("code");
        const error = url.searchParams.get("error");
        const errorDescription = url.searchParams.get("error_description");
        // For the debug log; the redirect below reads the param itself. Left
        // undefaulted because a default would pass the safety guard, so any branch
        // on it in that chain matches every param-less sign-in and masks the
        // fallbacks beneath it.
        const next = url.searchParams.get("next");

        console.log("[Auth Callback Debug] URL parameters:", {
          hasCode: !!code,
          hasError: !!error,
          error,
          errorDescription,
          next,
          fullUrl: window.location.href,
        });

        // Handle OAuth errors
        if (error) {
          const errorMsg = errorDescription || error;
          console.error("[Auth Callback Debug] OAuth error:", {
            error,
            errorDescription,
          });

          setState({
            status: "error",
            message: t(
              "auth.callback.failedWithReason",
              "Authentication failed: {{error}}",
              { error: errorMsg },
            ),
            details: { error, errorDescription },
          });

          // Redirect to login page after 3 seconds
          setTimeout(() => navigate("/login", { replace: true }), 3000);
          return;
        }

        // If PKCE/SSR-style code is present, exchange it for a session
        if (code) {
          console.log("[Auth Callback Debug] Exchanging code for session...");

          setState({
            status: "processing",
            message: t(
              "auth.callback.exchanging",
              "Exchanging authorization code...",
            ),
          });

          const { data, error: exchangeError } =
            await supabase.auth.exchangeCodeForSession(code);

          if (exchangeError) {
            console.error(
              "[Auth Callback Debug] Code exchange error:",
              exchangeError,
            );

            setState({
              status: "error",
              message: t(
                "auth.callback.signInFailed",
                "Failed to complete sign in: {{error}}",
                {
                  error: exchangeError.message,
                },
              ),
              details: { exchangeError },
            });

            setTimeout(() => navigate("/login", { replace: true }), 3000);
            return;
          }

          console.log("[Auth Callback Debug] Code exchange successful:", {
            hasSession: !!data.session,
            userId: data.session?.user?.id,
            email: data.session?.user?.email,
          });

          setState({
            status: "success",
            message: t(
              "auth.callback.success",
              "Sign in successful! Redirecting...",
            ),
            details: {
              userId: data.session?.user?.id,
              email: data.session?.user?.email,
              provider: data.session?.user?.app_metadata?.provider,
            },
          });
        } else {
          // No code present - might already be authenticated
          console.log(
            "[Auth Callback Debug] No code present, checking existing session...",
          );

          const { data: sessionData } = await supabase.auth.getSession();

          if (sessionData.session) {
            console.log("[Auth Callback Debug] Existing session found");
            setState({
              status: "success",
              message: t(
                "auth.callback.alreadySignedIn",
                "Already signed in! Redirecting...",
              ),
            });
          } else {
            console.log("[Auth Callback Debug] No session found");
            setState({
              status: "error",
              message: t(
                "auth.callback.noData",
                "No authentication data found",
              ),
            });
            setTimeout(() => navigate("/login", { replace: true }), 2000);
            return;
          }
        }

        // A deliberate `next` outranks a remembered intent so it cannot be hijacked;
        // a remembered one is all a sign-up has, its confirmation link being unable
        // to carry a `next`. Claimed up front because reaching here means the detour
        // is over, so the intent is spent whichever wins.
        const explicitNext =
          url.searchParams.get("next") ?? url.searchParams.get("from");
        const pendingConnect = readPendingConnect();
        const remembered = takePendingDestination();
        const destination = isSafePostLoginRedirect(explicitNext)
          ? explicitNext
          : pendingConnect
            ? `/link?request=${encodeURIComponent(pendingConnect)}`
            : (remembered ?? (await resolveLandingPath()));
        console.log("[Auth Callback Debug] Redirecting to:", destination);

        setTimeout(() => navigate(destination, { replace: true }), 1500);
      } catch (err) {
        console.error("[Auth Callback Debug] Unexpected error:", err);

        setState({
          status: "error",
          message: t("login.unexpectedError", "Unexpected error: {{message}}", {
            message:
              err instanceof Error
                ? err.message
                : t("auth.callback.unknownError", "Unknown error"),
          }),
          details: { error: err },
        });

        setTimeout(() => navigate("/login", { replace: true }), 3000);
      }
    };

    handleCallback();
  }, [navigate]);

  const getTitle = () => {
    switch (state.status) {
      case "processing":
        return t("auth.callback.title.processing", "Signing you in");
      case "success":
        return t("auth.callback.title.success", "You're all set!");
      case "error":
        return t("oauth.error.title", "Authentication failed");
      default:
        return t("auth.callback.title.default", "Authentication");
    }
  };

  return (
    <AuthShell>
      <div className="auth-logo-block">
        <img
          src={loginHeader}
          alt="Stirling PDF"
          className="auth-logo-header auth-logo-header--light"
        />
        <img
          src={withBasePath("/modern-logo/LoginDarkModeHeader.svg")}
          alt="Stirling PDF"
          className="auth-logo-header auth-logo-header--dark"
        />
      </div>

      <h1 className="login-title" style={{ textAlign: "center" }}>
        {getTitle()}
      </h1>

      {state.status === "error" ? (
        <ErrorMessage error={state.message} />
      ) : (
        <p className="login-subtitle" style={{ textAlign: "center" }}>
          {state.message}
        </p>
      )}

      {state.status === "processing" && (
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            margin: "1rem 0",
          }}
        >
          <Spinner size="md" />
        </div>
      )}

      {state.status === "error" && (
        <div className="auth-section">
          <Button
            accent="danger"
            fullWidth
            onClick={() => navigate("/login", { replace: true })}
          >
            {t("auth.callback.backToLogin", "Back to login")}
          </Button>
        </div>
      )}

      {import.meta.env.DEV && state.details && (
        <details className="mt-6 text-left">
          <summary className="cursor-pointer text-sm text-gray-500 hover:text-gray-700">
            Debug Information
          </summary>
          <pre className="mt-2 p-3 bg-gray-100 rounded text-xs overflow-auto">
            {JSON.stringify(state.details, null, 2)}
          </pre>
        </details>
      )}
    </AuthShell>
  );
}