Skip to content

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

18.7 KB
Raw Blame
import { useEffect, useMemo, useRef, useState } from "react";
import {
  type Location,
  Navigate,
  useLocation,
  useNavigate,
  useSearchParams,
} from "react-router-dom";
import { Button } from "@editor/ui/Button";
import { isSafePostLoginRedirect } from "@editor/auth";
import {
  setPostLoginRedirectPath,
  consumePostLoginRedirectPath,
} from "@editor/auth/spring/springAuthClient";
import { useAuth } from "@editor/auth/UseSession";
import { useAppConfig } from "@editor/contexts/AppConfigContext";
import { useTranslation } from "react-i18next";
import { useDocumentMeta } from "@editor/hooks/useDocumentMeta";
import AuthLayout from "@editor/routes/authShared/AuthLayout";
import { useBackendProbe } from "@editor/hooks/useBackendProbe";
import { EDITOR_BASENAME } from "@editor/routes/editorBasename";
import { resolveLandingPath } from "@editor/utils/loginLanding";
import { BASE_PATH, withBasePath } from "@editor/constants/app";
import { updateSupportedLanguages } from "@editor/i18n";
import SpringLoginForm from "@editor/auth/ui/SpringLoginForm";
import AuthDefaultCredentials from "@editor/auth/ui/AuthDefaultCredentials";
import { SetupSignInScreen } from "@editor/components/serverSetup/SetupScreen";
import { markSetupSignIn } from "@editor/components/serverSetup/setupSignInHandoff";
import { DEFAULT_ADMIN_CREDENTIALS } from "@editor/auth/defaultCredentials";
import { springAuth } from "@editor/auth/spring/springAuthClient";
import { useSpringLogin } from "@editor/auth/ui/useSpringLogin";
import {
  clearSignedOutFlag,
  hasSignedOutInThisTab,
  isSsoAutoLoginAllowed,
  recordSsoAutoLoginAttempt,
  recordSsoAutoLoginError,
  resetSsoAutoLoginCounts,
} from "@editor/auth/ssoAutoLogin";
import { LoadingFallback } from "@editor/components/shared/LoadingFallback";
import loginHeader from "@editor/assets/brand/modern-logo/LoginLightModeHeader.svg";

// A failed default sign-in counts towards the admin's lockout, so a tab that
// saw one fail (or can't read storage) never tries again.
const DEFAULT_SIGN_IN_FAILED_KEY = "stirling_default_sign_in_failed";

function defaultSignInFailedInThisTab(): boolean {
  try {
    return window.sessionStorage.getItem(DEFAULT_SIGN_IN_FAILED_KEY) === "1";
  } catch {
    return true;
  }
}

function recordDefaultSignInFailure(): void {
  try {
    window.sessionStorage.setItem(DEFAULT_SIGN_IN_FAILED_KEY, "1");
  } catch {
    // Storage blocked: the read above already stops the next attempt.
  }
}

export default function Login() {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const { session, loading } = useAuth();
  // Reuses the shared guard rather than re-deriving one: same-origin relative
  // paths only, rejecting "//host", "/\host" (browsers normalise the backslash)
  // and auth routes (a ?from=/login would cost a pointless hop back here).
  const safePath = (path: unknown): string | null =>
    isSafePostLoginRedirect(path) ? path : null;

  // Where to return to after signing in. Router state first (set when Landing
  // bounces an unauthenticated visitor), then the query, which is what survives
  // a reload of /login. Null means "no specific destination" and the caller
  // falls back to the default landing.
  const resolveReturnPath = (): string | null => {
    const fromState = (location.state as { from?: Partial<Location> } | null)
      ?.from;
    if (fromState?.pathname) {
      return safePath(
        fromState.pathname + (fromState.search ?? "") + (fromState.hash ?? ""),
      );
    }
    const fromQuery = searchParams.get("from");
    if (!fromQuery) return null;
    try {
      return safePath(decodeURIComponent(fromQuery));
    } catch {
      return safePath(fromQuery);
    }
  };
  const { refetch } = useAppConfig();
  const { t } = useTranslation();
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [showEmailForm, setShowEmailForm] = useState(true);
  const [_enableLogin, setEnableLogin] = useState<boolean | null>(null);
  const [ssoAutoLogin, setSsoAutoLogin] = useState(false);
  const backendProbe = useBackendProbe();
  const [isFirstTimeSetup, setIsFirstTimeSetup] = useState(false);
  const [showDefaultCredentials, setShowDefaultCredentials] = useState(false);
  const [defaultSignInAllowed, setDefaultSignInAllowed] = useState(false);
  const [loginConfigLoaded, setLoginConfigLoaded] = useState(false);
  const loginDisabled =
    backendProbe.loginDisabled === true || _enableLogin === false;
  const autoLoginAttempted = useRef(false);
  const defaultSignInAttempted = useRef(false);
  const [defaultSignIn, setDefaultSignIn] = useState<
    "idle" | "signingIn" | "signedIn" | "failed"
  >("idle");
  const autoLoginErrorRecorded = useRef(false);

  const errorFromState = (location.state as { error?: string } | null)?.error;
  const errorFromQuery = useMemo(() => {
    if (!searchParams) {
      return null;
    }
    const errorParamKeys = [
      "error",
      "error_description",
      "error_code",
      "sso_error",
      "oauth_error",
      "saml_error",
      "login_error",
    ];
    for (const key of errorParamKeys) {
      const value = searchParams.get(key);
      if (value) {
        return value;
      }
    }
    for (const [key, value] of searchParams.entries()) {
      if (key.toLowerCase().includes("error")) {
        return value || "Single sign-on failed. Please try again.";
      }
    }
    return null;
  }, [searchParams]);

  const hasSsoLoginError = Boolean(errorFromState || errorFromQuery);
  // /login?all is how a local admin reaches the password form when SSO
  // auto-login would otherwise redirect straight to the provider.
  const skipSsoAutoLogin = searchParams.has("all");

  // Shared login state + sign-in handlers + provider fetch. Editor-specific
  // behaviour (auto-login, redirects, first-time setup) is layered on here.
  const login = useSpringLogin({
    ready: backendProbe.status === "up" || backendProbe.loginDisabled,
    redirectTo: `${BASE_PATH}/auth/callback`,
    onSignInStart: clearSignedOutFlag,
    onBeforeOAuth: () => {
      // Don't overwrite a path already stashed by httpErrorHandler on a 401.
      const returnPath = resolveReturnPath();
      if (returnPath) {
        setPostLoginRedirectPath(returnPath);
      }
    },
    onConfigLoaded: (data) => {
      // If login is disabled, redirect to home (anonymous mode)
      if (data.enableLogin === false) {
        navigate(EDITOR_BASENAME);
        return;
      }
      setEnableLogin(data.enableLogin ?? true);
      setSsoAutoLogin(Boolean(data.ssoAutoLogin));
      setIsFirstTimeSetup(data.firstTimeSetup ?? false);
      setShowDefaultCredentials(data.showDefaultCredentials ?? false);
      // Only an explicit yes: a server too old to send it never gets the attempt.
      setDefaultSignInAllowed(data.defaultSignIn === true);
      setLoginConfigLoaded(true);
      // Apply language configuration from server
      if (data.languages || data.defaultLocale) {
        updateSupportedLanguages(data.languages, data.defaultLocale);
      }
    },
  });

  const isUserPassAllowed = login.isUserPassAllowed;
  const isSsoOnlyMode = !login.isUserPassAllowed;
  // Visitors who can only sign in with a password: the admin of a fresh
  // install (default credentials) and a local account just created from an
  // invite (messageType). Redirecting them to the IdP strands them there.
  const awaitsPasswordSignIn =
    isUserPassAllowed && (isFirstTimeSetup || searchParams.has("messageType"));

  // Periodically probe while backend isn't up so the screen can auto-advance when it comes online
  useEffect(() => {
    if (backendProbe.status === "up" || backendProbe.loginDisabled) {
      return;
    }
    const tick = async () => {
      const result = await backendProbe.probe();
      if (result.status === "up") {
        await refetch();
        if (loginDisabled) {
          navigate(EDITOR_BASENAME, { replace: true });
        }
      }
    };
    const intervalId = window.setInterval(() => {
      void tick();
    }, 5000);
    return () => window.clearInterval(intervalId);
  }, [
    backendProbe.status,
    backendProbe.loginDisabled,
    backendProbe.probe,
    refetch,
    navigate,
    loginDisabled,
  ]);

  // Redirect immediately if user has valid session (JWT already validated by AuthProvider)
  useEffect(() => {
    if (loading) return;
    if (!session) return;
    resetSsoAutoLoginCounts();
    const stashed = consumePostLoginRedirectPath();
    const returnPath = resolveReturnPath() ?? stashed;
    if (returnPath) {
      navigate(returnPath, { replace: true });
      return;
    }
    // No explicit destination: the editor, unless this account opted in to the
    // processor. Resolved here rather than by bouncing through "/" so the app
    // isn't torn down and remounted on the way.
    let active = true;
    // Warm the editor chunk while /me resolves so the landing paints at once.
    void import("@editor/routes/Landing").catch(() => {});
    void resolveLandingPath().then(
      (path) => {
        if (!active) return;
        navigate(path, { replace: true });
      },
      () => {
        if (active) navigate(EDITOR_BASENAME, { replace: true });
      },
    );
    return () => {
      active = false;
    };
  }, [session, loading, navigate, location.state, searchParams]);

  // If backend reports login is disabled, redirect to home (anonymous mode)
  useEffect(() => {
    if (backendProbe.loginDisabled) {
      // Straight to the editor, not "/": with login disabled there is no role
      // to route on, and "/" would just bounce back here.
      const id = setTimeout(
        () => navigate(EDITOR_BASENAME, { replace: true }),
        0,
      );
      return () => clearTimeout(id);
    }
  }, [backendProbe.loginDisabled, navigate]);

  // The email/password form is always shown when username/password auth is
  // allowed; SSO-only mode hides it.
  useEffect(() => {
    const userPassAllowed =
      login.loginMethod === "all" || login.loginMethod === "normal";
    setShowEmailForm(userPassAllowed);
  }, [login.loginMethod]);

  // Auto-login to SSO when enabled and only one SSO option exists
  useEffect(() => {
    if (autoLoginAttempted.current) {
      return;
    }

    if (
      !ssoAutoLogin ||
      loginDisabled ||
      loading ||
      session ||
      backendProbe.status !== "up"
    ) {
      return;
    }

    if (
      skipSsoAutoLogin ||
      awaitsPasswordSignIn ||
      hasSsoLoginError ||
      !isSsoAutoLoginAllowed()
    ) {
      return;
    }

    if (login.providers.length !== 1) {
      return;
    }

    autoLoginAttempted.current = true;
    if (!recordSsoAutoLoginAttempt()) {
      return;
    }
    void login.signInWithProvider(login.providers[0]);
  }, [
    ssoAutoLogin,
    loginDisabled,
    loading,
    session,
    backendProbe.status,
    login.loginMethod,
    login.providers,
    login.signInWithProvider,
    hasSsoLoginError,
    skipSsoAutoLogin,
    awaitsPasswordSignIn,
  ]);

  // A server still in setup on the default login signs in by itself: the page
  // prints those credentials anyway. The server decides; otherwise, the form.
  const defaultSignInDue =
    defaultSignIn === "idle" &&
    defaultSignInAllowed &&
    login.isUserPassAllowed &&
    !hasSsoLoginError &&
    !hasSignedOutInThisTab() &&
    !session &&
    !defaultSignInFailedInThisTab();

  useEffect(() => {
    if (
      !defaultSignInDue ||
      defaultSignInAttempted.current ||
      loading ||
      session ||
      backendProbe.status !== "up"
    ) {
      return;
    }
    defaultSignInAttempted.current = true;
    setDefaultSignIn("signingIn");
    void springAuth
      .signInWithPassword({
        email: DEFAULT_ADMIN_CREDENTIALS.username,
        password: DEFAULT_ADMIN_CREDENTIALS.password,
      })
      .then(
        ({ session: signedIn, error }) => {
          if (error || !signedIn) {
            recordDefaultSignInFailure();
            setDefaultSignIn("failed");
            return;
          }
          markSetupSignIn();
          setDefaultSignIn("signedIn");
        },
        () => {
          recordDefaultSignInFailure();
          setDefaultSignIn("failed");
        },
      );
  }, [defaultSignInDue, loading, session, backendProbe.status]);

  // Handle query params (email prefill, success messages, and session expiry)
  useEffect(() => {
    try {
      const emailFromQuery = searchParams.get("email");
      if (emailFromQuery) {
        login.setEmail(emailFromQuery);
      }

      // Check if session expired (401 redirect)
      const expired = searchParams.get("expired");
      if (expired === "true") {
        login.setError(
          t(
            "login.sessionExpired",
            "Your session has expired. Please sign in again.",
          ),
        );
      }

      const messageType = searchParams.get("messageType");
      if (messageType) {
        switch (messageType) {
          case "accountCreated":
            setSuccessMessage(
              t(
                "login.accountCreatedSuccess",
                "Account created successfully! You can now sign in.",
              ),
            );
            break;
          case "passwordChanged":
            setSuccessMessage(
              t(
                "login.passwordChangedSuccess",
                "Password changed successfully! Please sign in with your new password.",
              ),
            );
            break;
          case "credsUpdated":
            setSuccessMessage(
              t(
                "login.credentialsUpdated",
                "Your credentials have been updated. Please sign in again.",
              ),
            );
            break;
        }
      }

      if (errorFromState) {
        login.setError(errorFromState);
      } else if (errorFromQuery) {
        login.setError(errorFromQuery);
      }

      if (hasSsoLoginError && !autoLoginErrorRecorded.current) {
        recordSsoAutoLoginError();
        autoLoginErrorRecorded.current = true;
      }
    } catch (_) {
      // ignore
    }
  }, [
    searchParams,
    t,
    errorFromState,
    errorFromQuery,
    hasSsoLoginError,
    login.setEmail,
    login.setError,
  ]);

  const baseUrl = window.location.origin + BASE_PATH;

  // Set document meta
  useDocumentMeta({
    title: `${t("login.title", "Sign in")} - Stirling PDF`,
    description: t(
      "app.description",
      "A free, private PDF editor you can run on any infrastructure.",
    ),
    ogTitle: `${t("login.title", "Sign in")} - Stirling PDF`,
    ogDescription: t(
      "app.description",
      "A free, private PDF editor you can run on any infrastructure.",
    ),
    ogImage: `${baseUrl}/og_images/home.png`,
    ogUrl: `${window.location.origin}${window.location.pathname}`,
  });

  // If login is disabled, short-circuit to home (avoids rendering the form after retry)
  if (loginDisabled) {
    return <Navigate to={EDITOR_BASENAME} replace />;
  }

  // Checked before the auth state and session: once signing in starts, this
  // card stays up until the app takes over, so nothing flashes in between.
  if (
    defaultSignInDue ||
    defaultSignIn === "signingIn" ||
    defaultSignIn === "signedIn"
  ) {
    return <SetupSignInScreen />;
  }

  // The form is only for visitors known to be signed out; splash until then.
  if (loading) {
    return <LoadingFallback />;
  }

  if (session) {
    return <LoadingFallback />;
  }

  if (backendProbe.loading) {
    return <LoadingFallback />;
  }

  // If backend isn't ready yet, show a lightweight status screen instead of the form
  if (backendProbe.status !== "up" && !loginDisabled) {
    const handleRetry = async () => {
      const result = await backendProbe.probe();
      if (result.status === "up") {
        await refetch();
        navigate("/", { replace: true });
      }
    };
    return (
      <AuthLayout>
        <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>
        <div
          className="auth-section"
          style={{
            padding: "1.5rem",
            marginTop: "1rem",
            borderRadius: "0.75rem",
            backgroundColor:
              "color-mix(in srgb, var(--c-primary) 8%, transparent)",
            border:
              "1px solid color-mix(in srgb, var(--c-primary) 20%, transparent)",
          }}
        >
          <p style={{ margin: "0 0 0.75rem 0", color: "var(--c-text)" }}>
            {t(
              "backendStartup.unreachable",
              "The application cannot currently connect to the backend. Verify the backend status and network connectivity, then try again.",
            )}
          </p>
          <Button
            type="button"
            onClick={handleRetry}
            className="auth-cta-button px-4 py-[0.75rem] rounded-[0.625rem] text-base font-semibold mt-5 border-0 cursor-pointer"
            style={{ width: "fit-content" }}
          >
            {t("backendStartup.retry", "Retry")}
          </Button>
        </div>
      </AuthLayout>
    );
  }

  // Until the login settings arrive it is unknown whether this server signs
  // in by itself, so the form would only flash up and vanish.
  if (!loginConfigLoaded) {
    return <LoadingFallback />;
  }

  return (
    <AuthLayout>
      <SpringLoginForm
        state={login}
        logoSrc={loginHeader}
        logoDarkSrc={withBasePath("/modern-logo/LoginDarkModeHeader.svg")}
        showEmailForm={showEmailForm}
        oauthCtaPrefix={
          isSsoOnlyMode ? t("login.signInWith", "Sign in with") : undefined
        }
        oauthUseNewStyle={isSsoOnlyMode}
        aboveError={
          successMessage ? (
            <div
              style={{
                padding: "1rem",
                marginBottom: "1rem",
                backgroundColor:
                  "color-mix(in srgb, var(--c-success) 10%, transparent)",
                border:
                  "1px solid color-mix(in srgb, var(--c-success) 30%, transparent)",
                borderRadius: "0.5rem",
                color: "var(--color-green-dark)",
              }}
            >
              <p
                style={{
                  margin: 0,
                  fontSize: "0.875rem",
                  textAlign: "center",
                }}
              >
                {successMessage}
              </p>
            </div>
          ) : undefined
        }
        footer={
          isFirstTimeSetup &&
          showDefaultCredentials &&
          isUserPassAllowed &&
          defaultSignIn !== "failed" ? (
            <AuthDefaultCredentials />
          ) : undefined
        }
      />
    </AuthLayout>
  );
}