#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { resolveLandingPath } from "@editor/utils/loginLanding";
import { supabase, signInAnonymously } from "@editor/auth/supabase";
import { Button } from "@editor/ui/Button";
import { useAuth } from "@editor/auth/UseSession";
import { useTranslation } from "@editor/hooks/useTranslation";
import { useDocumentMeta } from "@editor/hooks/useDocumentMeta";
import AuthLayout from "@editor/routes/authShared/AuthLayout";
import "@editor/auth/ui/auth.css";
import "@editor/routes/authShared/saas-auth.css";
import {
absoluteWithBasePath,
getBaseUrl,
withBasePath,
} from "@editor/constants/app";
import { isSafePostLoginRedirect } from "@editor/services/postLoginRedirect";
import {
clearPendingDestination,
rememberPendingDestination,
takePendingDestination,
} from "@editor/services/pendingDestination";
import { Icon } from "@editor/ui/Icon";
// Import login components
import ErrorMessage from "@editor/auth/ui/ErrorMessage";
import EmailPasswordForm from "@editor/routes/login/EmailPasswordForm";
import OAuthButtons from "@editor/routes/login/OAuthButtons";
import LoggedInState from "@editor/routes/login/LoggedInState";
import { LoadingFallback } from "@editor/components/shared/LoadingFallback";
import loginHeader from "@editor/assets/brand/modern-logo/LoginLightModeHeader.svg";
import { PrivateContent } from "@editor/components/shared/PrivateContent";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
export default function Login() {
const navigate = useNavigate();
const { session, isAnonymous, loading, refreshSession } = useAuth();
// A guest session is not a sign-in: guests come here to sign in, so they get the form.
const signedIn = !!session && !isAnonymous;
const { t } = useTranslation();
const [isSigningIn, setIsSigningIn] = useState(false);
const [error, setError] = useState<string | null>(null);
const [showMagicLinkForm, setShowMagicLinkForm] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [magicLinkEmail, setMagicLinkEmail] = useState("");
const [magicLinkSent, setMagicLinkSent] = useState(false);
// Prefill email from query param (e.g. after password reset)
useEffect(() => {
try {
const url = new URL(window.location.href);
const emailFromQuery = url.searchParams.get("email");
if (emailFromQuery) {
setEmail(emailFromQuery);
}
} catch (_) {
// ignore
}
}, []);
// Same-origin router path to return to after login (e.g. the OAuth consent
// page, or the editor a 401 bounced the user off). `?next=` is what this app
// writes; `?from=` is what the shared core 401 handler writes.
const nextPath = useMemo(() => {
try {
const params = new URL(window.location.href).searchParams;
const candidate = params.get("next") ?? params.get("from");
return isSafePostLoginRedirect(candidate) ? candidate : null;
} catch (_) {
return null;
}
}, []);
/** On to where the visitor was heading, which is then no longer remembered. */
const continueToNext = () => {
clearPendingDestination();
navigate(nextPath ?? "/", { replace: true });
};
useEffect(() => {
if (signedIn && !loading && nextPath) continueToNext();
}, [signedIn, loading, nextPath, navigate]);
// Stashed as well as held in the URL: leaving to create an account loses the
// query string, and the confirmation link cannot carry a `next`.
useEffect(() => {
if (nextPath && !signedIn) rememberPendingDestination(nextPath);
}, [nextPath, signedIn]);
const baseUrl = getBaseUrl();
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/saas/app.png`,
ogUrl: `${window.location.origin}${window.location.pathname}`,
});
// The form is only for visitors known to be signed out; splash until then.
if (loading) {
return <LoadingFallback />;
}
// Show logged in state if authenticated (unless bouncing back to `next`)
if (signedIn && !loading) {
if (nextPath) {
return null;
}
return <LoggedInState />;
}
const signInWithProvider = async (
provider: "github" | "google" | "apple" | "azure",
) => {
try {
setIsSigningIn(true);
setError(null);
const redirectTo =
absoluteWithBasePath("/auth/callback") +
(nextPath ? `?next=${encodeURIComponent(nextPath)}` : "");
console.log(`[Login] Signing in with ${provider}`);
const oauthOptions: {
redirectTo: string;
queryParams?: Record<string, string>;
} = { redirectTo };
if (provider === "apple") {
oauthOptions.queryParams = { scope: "email name" };
} else if (provider === "azure") {
oauthOptions.queryParams = { scope: "openid profile email" };
} else {
oauthOptions.queryParams = {
access_type: "offline",
prompt: "consent",
};
}
const { error } = await supabase.auth.signInWithOAuth({
provider,
options: oauthOptions,
});
if (error) {
console.error(`[Login] ${provider} error:`, error);
setError(
t("login.failedToSignIn", { provider, message: error.message }),
);
}
} catch (err) {
console.error(`[Login] Unexpected error:`, err);
setError(
t("login.unexpectedError", {
message: err instanceof Error ? err.message : "Unknown error",
}),
);
} finally {
setIsSigningIn(false);
}
};
const signInWithEmail = async () => {
if (!email || !password) {
setError(t("login.pleaseEnterBoth"));
return;
}
try {
setIsSigningIn(true);
setError(null);
console.log("[Login] Signing in with email:", email);
const { data, error } = await supabase.auth.signInWithPassword({
email: email.trim(),
password: password,
});
if (error) {
console.error("[Login] Email sign in error:", error);
setError(error.message);
} else if (data.user) {
console.log("[Login] Email sign in successful");
// Claimed even when `nextPath` wins: the detour is over either way.
const remembered = takePendingDestination();
// Resolved here rather than by bouncing through "/", which would tear the app
// down and remount it on the way.
if (!nextPath) {
navigate(remembered ?? (await resolveLandingPath()), {
replace: true,
});
}
}
} catch (err) {
console.error("[Login] Unexpected error]:", err);
setError(
t("login.unexpectedError", {
message: err instanceof Error ? err.message : "Unknown error",
}),
);
} finally {
setIsSigningIn(false);
}
};
const signInWithMagicLink = async () => {
if (!magicLinkEmail) {
setError(t("login.pleaseEnterEmail"));
return;
}
try {
setIsSigningIn(true);
setError(null);
console.log("[Login] Sending magic link to:", magicLinkEmail);
const { error } = await supabase.auth.signInWithOtp({
email: magicLinkEmail.trim(),
options: {
emailRedirectTo:
absoluteWithBasePath("/auth/callback") +
(nextPath ? `?next=${encodeURIComponent(nextPath)}` : ""),
},
});
if (error) {
console.error("[Login] Magic link error:", error);
setError(error.message);
} else {
setError(null);
setMagicLinkSent(true);
}
} catch (err) {
setError(
t("login.unexpectedError", {
message: err instanceof Error ? err.message : "Unknown error",
}),
);
} finally {
setIsSigningIn(false);
}
};
const handleAnonymousSignIn = async () => {
// Already a guest: carry on as that guest. Signing in anonymously again would swap their
// session for a brand-new guest account.
if (session && isAnonymous) {
continueToNext();
return;
}
try {
setIsSigningIn(true);
setError(null);
console.log("[Login] Signing in anonymously");
const { data } = await signInAnonymously();
if (data.user) {
console.log(
"[Login] Anonymous sign in successful, refreshing session...",
);
await refreshSession();
// A guest session does not count as signed in here, so nothing else moves them on.
const remembered = takePendingDestination();
navigate(nextPath ?? remembered ?? (await resolveLandingPath()), {
replace: true,
});
}
} catch (err) {
console.error("[Login] Unexpected error:", err);
setError(
t("login.unexpectedError", {
message: err instanceof Error ? err.message : "Unknown error",
}),
);
} finally {
setIsSigningIn(false);
}
};
const toggleMagicLink = () => {
setShowMagicLinkForm((v) => !v);
setMagicLinkSent(false);
};
return (
<AuthLayout>
{/* Centered logo */}
<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>
<ErrorMessage error={error} />
{/* OAuth + magic link group — single flex column so gap is uniform */}
<div
style={{
display: "flex",
flexDirection: "column",
gap: "0.75rem",
marginBottom: "2.5rem",
}}
>
<OAuthButtons
onProviderClick={signInWithProvider}
isSubmitting={isSigningIn}
layout="fullwidth"
labelPrefix={`${t("login.signInWith", "Sign in with")} `}
/>
{/* Magic link button + its expandable form as one unit */}
<div>
<Button
variant="secondary"
disabled={isSigningIn}
onClick={toggleMagicLink}
className={`oauth-button-fullwidth auth-expandable-trigger ${showMagicLinkForm ? "auth-expandable-trigger--active" : ""}`}
>
<span className="oauth-btn-group">
<Icon
name="link"
className="oauth-icon-medium"
style={{ marginRight: "0.5rem", flexShrink: 0 }}
/>
<span className="oauth-btn-label">
{t("login.useMagicLink", "Use magic link")}
</span>
</span>
</Button>
<div
className={`auth-expand-grid ${showMagicLinkForm ? "auth-expand-grid--open" : ""}`}
>
<div className="auth-expand-inner">
<div style={{ paddingTop: "0.25rem" }}>
{magicLinkSent ? (
<p
style={{
fontSize: "0.875rem",
color: "var(--color-green-dark)",
margin: 0,
}}
>
<PrivateContent>
{t("login.magicLinkSent", { email: magicLinkEmail })}
</PrivateContent>
</p>
) : (
<div className="auth-magic-row">
<input
type="email"
placeholder={t(
"login.enterEmailForMagicLink",
"Enter your email",
)}
value={magicLinkEmail}
onChange={(e) => setMagicLinkEmail(e.target.value)}
onKeyDown={(e) =>
e.key === "Enter" &&
!isSigningIn &&
signInWithMagicLink()
}
className={`auth-input ${privateContentClassName}`}
/>
<Button
onClick={signInWithMagicLink}
disabled={isSigningIn || !magicLinkEmail}
className="auth-magic-button"
>
{isSigningIn
? t("login.sending")
: t("login.sendMagicLink")}
</Button>
</div>
)}
</div>
</div>
</div>
</div>
</div>
{/* Email + password form — always visible (no expander toggle) */}
<div style={{ paddingBottom: "0.5rem" }}>
<EmailPasswordForm
email={email}
password={password}
setEmail={setEmail}
setPassword={setPassword}
onSubmit={signInWithEmail}
isSubmitting={isSigningIn}
submitButtonText={
isSigningIn ? t("login.loggingIn") : t("login.login")
}
/>
<Button
variant="tertiary"
onClick={() => navigate("/auth/reset")}
className="auth-link-black"
style={{ fontSize: "0.8125rem", marginTop: "0.25rem" }}
>
{t("login.forgotPassword", "Forgot your password?")}
</Button>
</div>
{/* Create an account — pushed to the bottom */}
<div
style={{
textAlign: "center",
marginTop: "auto",
paddingTop: "1rem",
}}
>
<Button
variant="tertiary"
onClick={() =>
navigate(
"/signup" +
(nextPath ? `?next=${encodeURIComponent(nextPath)}` : ""),
)
}
style={{
background: "none",
border: "none",
cursor: "pointer",
fontSize: "0.875rem",
color: "var(--c-accent-text)",
}}
>
{t("login.createAccount", "Create an account")}
</Button>
</div>
{/* Skip — small + muted, at the very bottom */}
<div style={{ textAlign: "center", margin: "0.5rem 0 0.25rem" }}>
<Button
variant="tertiary"
onClick={handleAnonymousSignIn}
disabled={isSigningIn}
style={{
background: "none",
border: "none",
cursor: "pointer",
fontSize: "0.8125rem",
fontWeight: 500,
color: "var(--c-text-subtle)",
}}
>
{isSigningIn
? t("login.signingIn", "Signing in...")
: `${t("signup.skip", "Skip")} →`}
</Button>
</div>
</AuthLayout>
);
}