import React, { useCallback, useEffect, useRef, useState } from "react"; import { Alert, Box, Button, Checkbox, Divider, FormControlLabel, TextField, Typography } from "@mui/material"; import { useLocation, useNavigate } from "react-router-dom"; import { api, getApiErrorMessage } from "../api"; import { getRememberMePref, safeAuthReturnPath, setAuthPersistencePreference } from "../auth"; import GoogleAuthCard from "../components/GoogleAuthCard"; import MicrosoftAuthCard from "../components/MicrosoftAuthCard"; import TwoFactorChallenge from "../components/TwoFactorChallenge"; import TurnstileWidget from "../components/TurnstileWidget"; import { useToast } from "../toast"; import { useI18n } from "../i18n/I18nProvider"; import type { TranslationKey } from "../i18n/translations"; import AuthPageFrame from "../layout/AuthPageFrame"; type AuthConfig = { requireAuth: boolean; googleEnabled: boolean; microsoftEnabled: boolean; localEnabled: boolean; allowRegistration: boolean; requireEmailVerification: boolean; turnstileEnabled?: boolean; turnstileSiteKey?: string; }; export default function LoginPage({ initialMode = "login" }: { initialMode?: "login" | "register" }) { const { toast } = useToast(); const { t } = useI18n(); const currentTranslation = useRef(t); currentTranslation.current = t; const navigate = useNavigate(); const location = useLocation() as any; const [cfg, setCfg] = useState(null); const [configLoading, setConfigLoading] = useState(true); const [configFailed, setConfigFailed] = useState(false); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [rememberMe, setRememberMe] = useState(() => getRememberMePref()); const [loading, setLoading] = useState(false); const [pendingToken, setPendingToken] = useState(null); const [emailNotVerified, setEmailNotVerified] = useState(false); const [resendingVerification, setResendingVerification] = useState(false); const [verificationResent, setVerificationResent] = useState(false); const [fieldErrors, setFieldErrors] = useState<{ email?: TranslationKey; password?: TranslationKey; confirmPassword?: TranslationKey }>({}); const [registerMode, setRegisterMode] = useState(initialMode === "register"); const [turnstileToken, setTurnstileToken] = useState(""); const [submitError, setSubmitError] = useState<{ cause: unknown; fallback: TranslationKey } | null>(null); const emailRef = useRef(null); const passwordRef = useRef(null); const confirmPasswordRef = useRef(null); const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const returnPath = new URLSearchParams(location.search).has("sessionChanged") ? undefined : safeAuthReturnPath(location.state?.from); const nextPath = returnPath ?? "/dashboard"; const fromState = location.state?.fromState; const contextPath = returnPath && safeAuthReturnPath(fromState?.from); const nextOptions = contextPath ? { replace: true, state: { from: contextPath, ...(Number.isSafeInteger(fromState.focusJobId) && fromState.focusJobId > 0 ? { focusJobId: fromState.focusJobId } : {}) }, } : { replace: true }; const loadAuthConfig = useCallback(() => { setConfigLoading(true); setConfigFailed(false); return api .get("/auth/config") .then((r) => setCfg(r.data)) .catch(() => { setCfg(null); setConfigFailed(true); }) .finally(() => setConfigLoading(false)); }, []); useEffect(() => { void loadAuthConfig(); }, [loadAuthConfig]); async function completeLogin() { setAuthPersistencePreference(rememberMe ? "local" : "session"); await api.get("/auth/me"); toast(currentTranslation.current("signedIn"), "success"); navigate(nextPath, nextOptions); } function validate(mode: "login" | "register") { const errors: { email?: TranslationKey; password?: TranslationKey; confirmPassword?: TranslationKey } = {}; if (!email.trim()) errors.email = mode === "login" ? "usernameOrEmailRequired" : "emailRequired"; else if (mode === "register" && !EMAIL_PATTERN.test(email.trim())) errors.email = "invalidEmail"; if (!password) errors.password = "passwordRequired"; else if (mode === "register" && password.length < 8) errors.password = "passwordTooShort"; if (mode === "register" && password && confirmPassword !== password) { errors.confirmPassword = "passwordsDoNotMatch"; } setFieldErrors(errors); if (errors.email) emailRef.current?.focus(); else if (errors.password) passwordRef.current?.focus(); else if (errors.confirmPassword) confirmPasswordRef.current?.focus(); return Object.keys(errors).length === 0; } async function submit(mode: "login" | "register") { if (!validate(mode)) return; setLoading(true); setSubmitError(null); setEmailNotVerified(false); setVerificationResent(false); try { const url = mode === "register" ? "/auth/register" : "/auth/login"; const payload = { email, password, rememberMe, ...(cfg?.turnstileEnabled ? { turnstileToken } : {}) }; const res = await api.post<{ requiresTwoFactor?: boolean; pendingToken?: string; verificationRequired?: boolean }>(url, payload); if (res.data?.verificationRequired) { setEmailNotVerified(true); toast(currentTranslation.current("registerCheckEmailForVerification"), "info"); return; } if (res.data?.requiresTwoFactor && res.data.pendingToken) { setPendingToken(res.data.pendingToken); return; } await completeLogin(); } catch (e: any) { if (mode === "login" && e?.response?.data?.error === "email_not_verified") { setEmailNotVerified(true); } else { setSubmitError({ cause: e, fallback: "loginFailed" }); } } finally { setLoading(false); } } async function resendVerification() { setResendingVerification(true); setSubmitError(null); try { await api.post("/auth/resend-verification-email", { email }); setVerificationResent(true); toast(currentTranslation.current("verificationEmailResent"), "success"); } catch (e: any) { setSubmitError({ cause: e, fallback: "verifyEmailFailed" }); } finally { setResendingVerification(false); } } const allowReg = cfg?.allowRegistration ?? false; return ( {configLoading ? {t("loading")} : null} {configFailed ? void loadAuthConfig()}>{t("retry")}}> {t("appErrorBody")} : null} {new URLSearchParams(location.search).has("sessionChanged") ? {t("sessionChangedCleared")} : null} {pendingToken ? ( setPendingToken(null)} onSuccess={() => { setPendingToken(null); void completeLogin(); }} /> ) : ( <> { e.preventDefault(); void submit(registerMode ? "register" : "login"); }} sx={{ display: "flex", flexDirection: "column", gap: 1.5 }} > {submitError ? {getApiErrorMessage(submitError.cause, t(submitError.fallback))} : null} {registerMode && cfg && !allowReg ? {t("registrationUnavailable")} : null} {cfg?.requireEmailVerification && emailNotVerified && ( void resendVerification()}> {verificationResent ? t("verificationEmailResent") : t("resendVerificationEmail")} } > {t("emailNotVerified")} )} { setEmail(e.target.value); setFieldErrors((f) => ({ ...f, email: undefined })); }} autoComplete={registerMode ? "email" : "username"} autoFocus inputRef={emailRef} error={Boolean(fieldErrors.email)} helperText={fieldErrors.email ? t(fieldErrors.email) : undefined} fullWidth /> { setPassword(e.target.value); setFieldErrors((f) => ({ ...f, password: undefined, confirmPassword: undefined })); }} autoComplete={registerMode ? "new-password" : "current-password"} inputRef={passwordRef} type="password" error={Boolean(fieldErrors.password)} helperText={fieldErrors.password ? t(fieldErrors.password) : registerMode ? t("passwordTooShort") : undefined} fullWidth /> {registerMode && ( { setConfirmPassword(e.target.value); setFieldErrors((f) => ({ ...f, confirmPassword: undefined })); }} autoComplete="new-password" inputRef={confirmPasswordRef} type="password" error={Boolean(fieldErrors.confirmPassword)} helperText={fieldErrors.confirmPassword ? t(fieldErrors.confirmPassword) : undefined} fullWidth /> )} {!registerMode && ( setRememberMe(e.target.checked)} />} label={t("rememberMe")} /> )} {!registerMode && ( {rememberMe ? t("rememberMeHelpPersistent") : t("rememberMeHelpSession")} )} {cfg?.turnstileEnabled && cfg.turnstileSiteKey ? ( ) : null} {(allowReg || initialMode === "register") && ( )} {loading || resendingVerification ? {t("loading")} : null} {!registerMode && (cfg?.googleEnabled || cfg?.microsoftEnabled) ? ( {t("or")} {cfg?.googleEnabled ? { navigate(nextPath, nextOptions); }} /> : null} {cfg?.microsoftEnabled ? { navigate(nextPath, nextOptions); }} /> : null} ) : null} )} ); }