287 lines
14 KiB
TypeScript
287 lines
14 KiB
TypeScript
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 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 navigate = useNavigate();
|
|
const location = useLocation() as any;
|
|
|
|
const [cfg, setCfg] = useState<AuthConfig | null>(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<string | null>(null);
|
|
const [emailNotVerified, setEmailNotVerified] = useState(false);
|
|
const [resendingVerification, setResendingVerification] = useState(false);
|
|
const [verificationResent, setVerificationResent] = useState(false);
|
|
const [fieldErrors, setFieldErrors] = useState<{ email?: string; password?: string; confirmPassword?: string }>({});
|
|
const [registerMode, setRegisterMode] = useState(initialMode === "register");
|
|
const [turnstileToken, setTurnstileToken] = useState("");
|
|
const [submitError, setSubmitError] = useState<string | null>(null);
|
|
const emailRef = useRef<HTMLInputElement>(null);
|
|
const passwordRef = useRef<HTMLInputElement>(null);
|
|
const confirmPasswordRef = useRef<HTMLInputElement>(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<AuthConfig>("/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(t("signedIn"), "success");
|
|
navigate(nextPath, nextOptions);
|
|
}
|
|
|
|
function validate(mode: "login" | "register") {
|
|
const errors: { email?: string; password?: string; confirmPassword?: string } = {};
|
|
if (!email.trim()) errors.email = mode === "login" ? t("usernameOrEmailRequired") : t("emailRequired");
|
|
else if (mode === "register" && !EMAIL_PATTERN.test(email.trim())) errors.email = t("invalidEmail");
|
|
|
|
if (!password) errors.password = t("passwordRequired");
|
|
else if (mode === "register" && password.length < 8) errors.password = t("passwordTooShort");
|
|
|
|
if (mode === "register" && password && confirmPassword !== password) {
|
|
errors.confirmPassword = t("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(t("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(getApiErrorMessage(e, t("loginFailed")));
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
async function resendVerification() {
|
|
setResendingVerification(true);
|
|
setSubmitError(null);
|
|
try {
|
|
await api.post("/auth/resend-verification-email", { email });
|
|
setVerificationResent(true);
|
|
toast(t("verificationEmailResent"), "success");
|
|
} catch (e: any) {
|
|
setSubmitError(getApiErrorMessage(e, t("verifyEmailFailed")));
|
|
} finally {
|
|
setResendingVerification(false);
|
|
}
|
|
}
|
|
|
|
const allowReg = cfg?.allowRegistration ?? false;
|
|
|
|
return (
|
|
<AuthPageFrame title={registerMode ? t("createAccount") : t("signInTitle")} description={cfg ? (cfg.requireAuth ? t("authRequired") : t("authOptional")) : undefined}>
|
|
{configLoading ? <Typography role="status" aria-live="polite" variant="body2" color="text.secondary" sx={{ mb: 2 }}>{t("loading")}</Typography> : null}
|
|
{configFailed ? <Alert severity="error" sx={{ mb: 2 }} action={<Button type="button" color="inherit" size="small" onClick={() => void loadAuthConfig()}>{t("retry")}</Button>}>
|
|
{t("appErrorBody")}
|
|
</Alert> : null}
|
|
{new URLSearchParams(location.search).has("sessionChanged") ? <Alert severity="info" sx={{ mb: 2 }}>{t("sessionChangedCleared")}</Alert> : null}
|
|
|
|
{pendingToken ? (
|
|
<TwoFactorChallenge
|
|
pendingToken={pendingToken}
|
|
onCancel={() => setPendingToken(null)}
|
|
onSuccess={() => { setPendingToken(null); void completeLogin(); }}
|
|
/>
|
|
) : (
|
|
<>
|
|
<Box
|
|
component="form"
|
|
onSubmit={(e) => { e.preventDefault(); void submit(registerMode ? "register" : "login"); }}
|
|
sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
|
|
>
|
|
{submitError ? <Alert severity="error">{submitError}</Alert> : null}
|
|
{registerMode && cfg && !allowReg ? <Alert severity="info">{t("registrationUnavailable")}</Alert> : null}
|
|
{cfg?.requireEmailVerification && emailNotVerified && (
|
|
<Alert
|
|
severity="warning"
|
|
action={
|
|
<Button color="inherit" size="small" disabled={resendingVerification || verificationResent} onClick={() => void resendVerification()}>
|
|
{verificationResent ? t("verificationEmailResent") : t("resendVerificationEmail")}
|
|
</Button>
|
|
}
|
|
>
|
|
{t("emailNotVerified")}
|
|
</Alert>
|
|
)}
|
|
<TextField
|
|
label={registerMode ? t("profileEmail") : t("usernameOrEmail")}
|
|
type={registerMode ? "email" : "text"}
|
|
value={email}
|
|
onChange={(e) => { setEmail(e.target.value); setFieldErrors((f) => ({ ...f, email: undefined })); }}
|
|
autoComplete={registerMode ? "email" : "username"}
|
|
autoFocus
|
|
inputRef={emailRef}
|
|
error={Boolean(fieldErrors.email)}
|
|
helperText={fieldErrors.email}
|
|
fullWidth
|
|
/>
|
|
<TextField
|
|
label={registerMode ? t("profileNewPassword") : t("profileCurrentPassword")}
|
|
value={password}
|
|
onChange={(e) => { 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 || (registerMode ? t("passwordTooShort") : undefined)}
|
|
fullWidth
|
|
/>
|
|
{registerMode && (
|
|
<TextField
|
|
label={t("confirmPassword")}
|
|
value={confirmPassword}
|
|
onChange={(e) => { setConfirmPassword(e.target.value); setFieldErrors((f) => ({ ...f, confirmPassword: undefined })); }}
|
|
autoComplete="new-password"
|
|
inputRef={confirmPasswordRef}
|
|
type="password"
|
|
error={Boolean(fieldErrors.confirmPassword)}
|
|
helperText={fieldErrors.confirmPassword}
|
|
fullWidth
|
|
/>
|
|
)}
|
|
|
|
{!registerMode && (
|
|
<Box sx={{ display: "flex", alignItems: { xs: "flex-start", sm: "center" }, justifyContent: "space-between", gap: 1, flexWrap: "wrap" }}>
|
|
<FormControlLabel
|
|
control={<Checkbox disableRipple checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} />}
|
|
label={t("rememberMe")}
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="text"
|
|
size="small"
|
|
disableRipple
|
|
onClick={() => navigate(`/forgot-password${email.trim() ? `?email=${encodeURIComponent(email.trim())}` : ""}`)}
|
|
sx={{ px: 0, minWidth: 0, fontWeight: 700, alignSelf: { xs: "stretch", sm: "auto" } }}
|
|
>
|
|
{t("forgotPassword")}
|
|
</Button>
|
|
</Box>
|
|
)}
|
|
|
|
{!registerMode && (
|
|
<Typography variant="body2" sx={{ color: "text.secondary", mt: -0.5 }}>
|
|
{rememberMe ? t("rememberMeHelpPersistent") : t("rememberMeHelpSession")}
|
|
</Typography>
|
|
)}
|
|
|
|
{cfg?.turnstileEnabled && cfg.turnstileSiteKey ? (
|
|
<TurnstileWidget key={registerMode ? "register" : "login"} siteKey={cfg.turnstileSiteKey} action={registerMode ? "register" : "login"} onToken={setTurnstileToken} />
|
|
) : null}
|
|
|
|
<Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 1, mt: 1, flexWrap: "wrap" }}>
|
|
{(allowReg || initialMode === "register") && (
|
|
<Button
|
|
type="button"
|
|
variant="text"
|
|
size="small"
|
|
disableRipple
|
|
disabled={loading}
|
|
onClick={() => { if (initialMode === "register") navigate("/login"); else setRegisterMode((v) => !v); setFieldErrors({}); setSubmitError(null); }}
|
|
sx={{ px: 0, minWidth: 0, fontWeight: 700, maxWidth: "100%", whiteSpace: "normal", overflowWrap: "anywhere" }}
|
|
>
|
|
{registerMode ? t("backToLogin") : t("createAccount")}
|
|
</Button>
|
|
)}
|
|
<Button type="submit" variant="contained" disableRipple disabled={loading || (registerMode && cfg !== null && !allowReg) || Boolean(cfg?.turnstileEnabled && !turnstileToken)} aria-busy={loading} sx={{ ml: "auto", maxWidth: "100%", whiteSpace: "normal", overflowWrap: "anywhere" }}>
|
|
{registerMode ? t("createAccount") : t("signInTitle")}
|
|
</Button>
|
|
</Box>
|
|
{loading || resendingVerification ? <Typography role="status" aria-live="polite" variant="body2" color="text.secondary">{t("loading")}</Typography> : null}
|
|
</Box>
|
|
|
|
{!registerMode && (cfg?.googleEnabled || cfg?.microsoftEnabled) ? (
|
|
<Box sx={{ mt: 2.5 }}>
|
|
<Divider sx={{ mb: 2 }}>{t("or")}</Divider>
|
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.25 }}>
|
|
{cfg?.googleEnabled ? <GoogleAuthCard presentation="sign-in" onSignedIn={() => { navigate(nextPath, nextOptions); }} /> : null}
|
|
{cfg?.microsoftEnabled ? <MicrosoftAuthCard presentation="sign-in" onSignedIn={() => { navigate(nextPath, nextOptions); }} /> : null}
|
|
</Box>
|
|
</Box>
|
|
) : null}
|
|
</>
|
|
)}
|
|
</AuthPageFrame>
|
|
);
|
|
}
|