feat(auth): migrate public authentication presentation

This commit is contained in:
cesnimda
2026-10-11 20:50:14 +02:00
parent 27c54146ad
commit 8ad720da5d
18 changed files with 7595 additions and 127 deletions
@@ -0,0 +1,27 @@
import React, { useId } from "react";
import { Box, Paper } from "@mui/material";
import { PageHeader } from "./PageLayout";
// Public auth pages own their forms, commands and token lifecycles.
export default function AuthPageFrame({ title, description, children }: {
title: string;
description?: string;
children: React.ReactNode;
}) {
const titleId = useId();
return (
<Box component="main" aria-labelledby={titleId} sx={{
minHeight: "100svh", display: "grid", placeItems: "center", boxSizing: "border-box",
p: "var(--app-page-gutter, 16px)", bgcolor: "background.default",
}}>
<Paper elevation={0} sx={{
width: "100%", maxWidth: 520, minWidth: 0, boxSizing: "border-box",
p: "var(--app-card-padding, 16px)", border: "1px solid", borderColor: "divider",
}}>
<PageHeader title={title} titleId={titleId} description={description} />
<Box sx={{ mt: "var(--app-section-gap, 24px)", minWidth: 0 }}>{children}</Box>
</Paper>
</Box>
);
}
+1 -1
View File
@@ -213,7 +213,7 @@ describe('LoginPage', () => {
renderLoginPage('register');
await userEvent.type(await screen.findByLabelText('Email'), 'pending@example.com');
await userEvent.type(screen.getByLabelText('Current password'), 'password1');
await userEvent.type(screen.getByLabelText('New password'), 'password1');
await userEvent.type(screen.getByLabelText('Confirm password'), 'password1');
await click(screen.getByRole('button', { name: 'Create account' }));
@@ -1,6 +1,6 @@
import React from "react";
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { api } from "./api";
@@ -42,3 +42,25 @@ test("legacy Microsoft recovery requires the emailed proof and a fresh matching
}));
expect(await screen.findByText("Microsoft sign-in was relinked. You can now sign in normally.")).toBeInTheDocument();
});
test("pending Microsoft recovery keeps a named action and announces progress before the real confirmation boundary", async () => {
process.env.NEXT_PUBLIC_MICROSOFT_CLIENT_ID = "test-client";
let resolvePopup!: (result: { idToken: string }) => void;
const popup = new Promise<{ idToken: string }>(resolve => { resolvePopup = resolve; });
(getMicrosoftMsalInstance as jest.Mock).mockReturnValue({
initialize: jest.fn().mockResolvedValue(undefined),
loginPopup: jest.fn().mockReturnValue(popup),
});
(api.post as jest.Mock).mockReset().mockResolvedValue({ data: {} });
window.history.replaceState({}, "", "/microsoft-legacy-relink?userId=user-1&tenantId=tenant-1&objectId=object-1&token=recovery-token");
render(<MemoryRouter><I18nProvider><MicrosoftLegacyRelinkPage /></I18nProvider></MemoryRouter>);
fireEvent.click(screen.getByRole("button", { name: "Continue with Microsoft" }));
expect(screen.getByRole("button", { name: "Continue with Microsoft" })).toBeDisabled();
expect(screen.getByRole("status")).toHaveTextContent("Loading...");
expect(api.post).not.toHaveBeenCalled();
await act(async () => resolvePopup({ idToken: "fresh-microsoft-token" }));
expect(await screen.findByRole("status")).toHaveTextContent("Microsoft sign-in was relinked.");
expect(api.post).toHaveBeenCalledWith("/auth/microsoft/legacy-relink/confirm", {
userId: "user-1", tenantId: "tenant-1", objectId: "object-1", recoveryToken: "recovery-token", microsoftToken: "fresh-microsoft-token",
});
});
@@ -0,0 +1,241 @@
import React from 'react';
import '@testing-library/jest-dom';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { api } from './api';
import { I18nProvider } from './i18n/I18nProvider';
import { ToastProvider } from './toast';
import ForgotPasswordPage from './views/ForgotPasswordPage';
import LoginPage from './views/LoginPage';
import MicrosoftLegacyRelinkPage from './views/MicrosoftLegacyRelinkPage';
import ResetPasswordPage from './views/ResetPasswordPage';
import VerifyEmailPage from './views/VerifyEmailPage';
const mockNavigate = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
const mockedApi = api as jest.Mocked<typeof api>;
function mount(view: React.ReactNode, path: string) {
window.history.replaceState({}, '', path);
return render(<MemoryRouter initialEntries={[path]}><I18nProvider><ToastProvider>{view}</ToastProvider></I18nProvider></MemoryRouter>);
}
function submit() {
fireEvent.submit(document.querySelector('form')!);
}
function deferred() {
let resolve!: (value: any) => void;
const promise = new Promise<any>(done => { resolve = done; });
return { promise, resolve };
}
beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
delete process.env.NEXT_PUBLIC_MICROSOFT_CLIENT_ID;
mockedApi.post.mockReset();
mockNavigate.mockReset();
mockedApi.get.mockReset().mockImplementation((url: string) => Promise.resolve({ data: url === '/auth/config'
? { requireAuth: true, googleEnabled: false, microsoftEnabled: false, localEnabled: true, allowRegistration: true, requireEmailVerification: true }
: { email: 'person@example.test', roles: [] } } as any));
});
describe('public auth presentation', () => {
it.each([
{ mode: 'login' as const, label: 'Current password', autocomplete: 'current-password', absent: 'New password' },
{ mode: 'register' as const, label: 'New password', autocomplete: 'new-password', absent: 'Current password' },
])('names the password field for $mode intent and retains its autocomplete contract', async ({ mode, label, autocomplete, absent }) => {
mount(<LoginPage initialMode={mode} />, mode === 'register' ? '/register' : '/login');
await screen.findByText('Authentication is required to use this app.');
expect(screen.getByLabelText(label, { exact: true })).toHaveAttribute('autocomplete', autocomplete);
expect(screen.getByLabelText(label, { exact: true })).toHaveAttribute('type', 'password');
expect(screen.queryByLabelText(absent, { exact: true })).not.toBeInTheDocument();
});
it.each([
{ name: 'password request', view: <ForgotPasswordPage />, path: '/forgot-password', title: 'Request a password reset' },
{ name: 'password reset', view: <ResetPasswordPage />, path: '/reset-password', title: 'Reset password' },
{ name: 'email verification', view: <VerifyEmailPage />, path: '/verify-email', title: 'Verify your email' },
{ name: 'email change', view: <VerifyEmailPage emailChange />, path: '/confirm-email-change', title: 'Confirm your new email' },
{ name: 'Microsoft recovery', view: <MicrosoftLegacyRelinkPage />, path: '/microsoft-legacy-relink', title: 'Recover Microsoft sign-in' },
])('provides one named main landmark and H1 for $name', async ({ view, path, title }) => {
mount(view, path);
const heading = await screen.findByRole('heading', { level: 1, name: title });
expect(screen.getAllByRole('main')).toHaveLength(1);
expect(screen.getByRole('main', { name: title })).toContainElement(heading);
expect(screen.getAllByRole('heading', { level: 1 })).toHaveLength(1);
});
it.each([
{ emailChange: false, path: '/verify-email?userId=user-1&token=pending', text: 'Verifying your email...' },
{ emailChange: true, path: '/confirm-email-change?userId=user-1&email=new%40example.test&token=pending', text: 'Confirming your new email...' },
])('announces the pending confirmation without an unnamed progressbar: $emailChange', async ({ emailChange, path, text }) => {
const request = deferred();
mockedApi.post.mockReturnValueOnce(request.promise);
mount(<VerifyEmailPage emailChange={emailChange} />, path);
expect(screen.getByRole('status')).toHaveTextContent(text);
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
await act(async () => request.resolve({ data: {} }));
expect(await screen.findByRole('status')).toHaveTextContent(emailChange ? 'Your email has changed.' : 'Your email has been verified.');
});
it('retains the entered reset email and a durable error in the page when the command fails', async () => {
mockedApi.post.mockRejectedValueOnce({ response: { status: 503, data: 'Reset delivery unavailable.' } });
mount(<ForgotPasswordPage />, '/forgot-password?email=prefilled%40example.test');
const email = screen.getByLabelText('Email');
fireEvent.change(email, { target: { value: 'person@example.test' } });
await act(async () => fireEvent.submit(email.closest('form')!));
const error = await within(screen.getByRole('main')).findByRole('alert');
expect(error).toHaveTextContent('Reset delivery unavailable.');
expect(email).toHaveValue('person@example.test');
expect(mockedApi.post).toHaveBeenCalledWith('/auth/request-password-reset', { email: 'person@example.test' });
expect(mockNavigate).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'Send reset link' })).toBeEnabled();
});
it('retains both new-password fields and the decoded recovery token after a rejected reset', async () => {
mockedApi.post.mockRejectedValueOnce({ response: { status: 400, data: 'Reset token expired.' } });
mount(<ResetPasswordPage />, '/reset-password?email=person%40example.test&token=encoded%2Btoken%2Fproof%3D');
fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'NewPassword123!' } });
fireEvent.change(screen.getByLabelText('Confirm password'), { target: { value: 'NewPassword123!' } });
await act(async () => fireEvent.submit(screen.getByLabelText('New password').closest('form')!));
expect(await within(screen.getByRole('main')).findByRole('alert')).toHaveTextContent('Reset token expired.');
expect(screen.getByLabelText('New password')).toHaveValue('NewPassword123!');
expect(screen.getByLabelText('Confirm password')).toHaveValue('NewPassword123!');
expect(mockedApi.post).toHaveBeenCalledWith('/auth/reset-password', {
email: 'person@example.test', token: 'encoded+token/proof=', newPassword: 'NewPassword123!',
});
expect(mockNavigate).not.toHaveBeenCalled();
});
it('keeps a rejected local sign-in beside the retained fields without navigating', async () => {
mockedApi.post.mockRejectedValueOnce({ response: { status: 401, data: 'Invalid credentials.' } });
mount(<LoginPage />, '/login');
fireEvent.change(await screen.findByLabelText('Username or email'), { target: { value: 'person' } });
fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'wrong-password' } });
await act(async () => submit());
expect(await within(screen.getByRole('main')).findByRole('alert')).toHaveTextContent('Invalid credentials.');
expect(screen.getByLabelText('Username or email')).toHaveValue('person');
expect(screen.getByLabelText('Current password')).toHaveValue('wrong-password');
expect(mockNavigate).not.toHaveBeenCalled();
});
it('keeps the reset-request action name while announcing an in-flight command', async () => {
const request = deferred();
mockedApi.post.mockReturnValueOnce(request.promise);
mount(<ForgotPasswordPage />, '/forgot-password?email=person%40example.test');
fireEvent.submit(screen.getByLabelText('Email').closest('form')!);
expect(screen.getByRole('button', { name: 'Send reset link' })).toBeDisabled();
expect(screen.getByRole('status')).toHaveTextContent('Sending reset link...');
await act(async () => request.resolve({ data: {} }));
expect(await within(screen.getByRole('main')).findByRole('status')).toHaveTextContent('If that account exists, a reset link has been sent.');
});
it('announces an in-flight local sign-in while preserving its action name', async () => {
const request = deferred();
mockedApi.post.mockReturnValueOnce(request.promise);
mount(<LoginPage />, '/login');
fireEvent.change(await screen.findByLabelText('Username or email'), { target: { value: 'person' } });
fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'Password123!' } });
submit();
expect(screen.getByRole('button', { name: 'Sign in' })).toBeDisabled();
expect(screen.getByRole('status')).toHaveTextContent('Loading...');
await act(async () => request.resolve({ data: {} }));
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/dashboard', { replace: true }));
});
it('announces a pending password save without changing its payload or successful destination', async () => {
const request = deferred();
mockedApi.post.mockReturnValueOnce(request.promise);
mount(<ResetPasswordPage />, '/reset-password?email=person%40example.test&token=good-token');
fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'NewPassword123!' } });
fireEvent.change(screen.getByLabelText('Confirm password'), { target: { value: 'NewPassword123!' } });
submit();
expect(screen.getByRole('button', { name: 'Update password' })).toBeDisabled();
expect(screen.getByRole('status')).toHaveTextContent('Saving…');
await act(async () => request.resolve({ data: {} }));
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/login', { replace: true }));
expect(mockedApi.post).toHaveBeenCalledWith('/auth/reset-password', { email: 'person@example.test', token: 'good-token', newPassword: 'NewPassword123!' });
});
it('focuses the first invalid local-login field and associates its explanation', async () => {
mount(<LoginPage />, '/login');
const email = await screen.findByLabelText('Username or email');
act(() => screen.getByLabelText('Current password').focus());
submit();
expect(email).toHaveFocus();
expect(email).toHaveAccessibleDescription('Username or email is required');
expect(mockedApi.post).not.toHaveBeenCalled();
});
it('focuses the invalid new password without losing confirmation input', () => {
mount(<ResetPasswordPage />, '/reset-password?email=person%40example.test&token=good-token');
const password = screen.getByLabelText('New password');
fireEvent.change(password, { target: { value: 'short' } });
fireEvent.change(screen.getByLabelText('Confirm password'), { target: { value: 'retained' } });
act(() => screen.getByLabelText('Confirm password').focus());
submit();
expect(password).toHaveFocus();
expect(password).toHaveAttribute('aria-invalid', 'true');
expect(password).toHaveAccessibleDescription('Password must be at least 8 characters, with a number and a lowercase letter.');
expect(screen.getByLabelText('Confirm password')).toHaveValue('retained');
expect(mockedApi.post).not.toHaveBeenCalled();
});
it('focuses and explains the invalid reset-request email without sending a command', () => {
mount(<ForgotPasswordPage />, '/forgot-password');
const email = screen.getByLabelText('Email');
act(() => email.blur());
fireEvent.submit(email.closest('form')!);
expect(email).toHaveFocus();
expect(email).toHaveAccessibleDescription('Enter your email address.');
expect(mockedApi.post).not.toHaveBeenCalled();
});
it('replaces previous reset-request success when a later request fails', async () => {
mockedApi.post.mockResolvedValueOnce({ data: {} } as any)
.mockRejectedValueOnce({ response: { status: 503, data: 'Reset delivery unavailable.' } });
mount(<ForgotPasswordPage />, '/forgot-password?email=person%40example.test');
await act(async () => submit());
expect(within(screen.getByRole('main')).getByRole('status')).toHaveTextContent('If that account exists, a reset link has been sent.');
await act(async () => submit());
expect(within(screen.getByRole('main')).getByRole('alert')).toHaveTextContent('Reset delivery unavailable.');
expect(within(screen.getByRole('main')).queryByRole('status')).not.toBeInTheDocument();
expect(screen.getByLabelText('Email')).toHaveValue('person@example.test');
});
it.each(['login', 'register'] as const)('does not assert optional authentication while %s configuration is unresolved', async (initialMode) => {
const configuration = deferred();
mockedApi.get.mockReturnValueOnce(configuration.promise);
mount(<LoginPage initialMode={initialMode} />, initialMode === 'register' ? '/register' : '/login');
expect(screen.queryByText('Authentication is optional in this environment.')).not.toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent('Loading...');
await act(async () => configuration.resolve({ data: {
requireAuth: false, googleEnabled: false, microsoftEnabled: false, localEnabled: true, allowRegistration: true, requireEmailVerification: false,
} }));
expect(screen.getByText('Authentication is optional in this environment.')).toBeInTheDocument();
});
it('offers a read-only configuration retry while retaining entered sign-in fields', async () => {
mockedApi.get.mockRejectedValueOnce({ response: { status: 503 } });
mount(<LoginPage />, '/login');
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith('/auth/config'));
fireEvent.change(screen.getByLabelText('Username or email'), { target: { value: 'retained-user' } });
fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'retained-password' } });
expect(screen.queryByText('Authentication is optional in this environment.')).not.toBeInTheDocument();
expect(within(screen.getByRole('main')).getByRole('alert')).toHaveTextContent('An unexpected error occurred while loading this page.');
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Retry' })));
expect(screen.getByText('Authentication is required to use this app.')).toBeInTheDocument();
expect(screen.getByLabelText('Username or email')).toHaveValue('retained-user');
expect(screen.getByLabelText('Current password')).toHaveValue('retained-password');
expect(mockedApi.get.mock.calls.filter(([path]) => path === '/auth/config')).toHaveLength(2);
expect(mockedApi.post).not.toHaveBeenCalled();
expect(mockNavigate).not.toHaveBeenCalled();
});
});
+19 -28
View File
@@ -1,12 +1,13 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import { Alert, Box, Button, Paper, TextField, Typography } from "@mui/material";
import { Alert, Box, Button, TextField, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
import AuthPageFrame from "../layout/AuthPageFrame";
export default function ForgotPasswordPage() {
const { toast } = useToast();
@@ -17,6 +18,8 @@ export default function ForgotPasswordPage() {
const [loading, setLoading] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [emailError, setEmailError] = useState<string | undefined>(undefined);
const [submitError, setSubmitError] = useState<string | null>(null);
const emailRef = useRef<HTMLInputElement>(null);
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
useEffect(() => {
@@ -25,25 +28,7 @@ export default function ForgotPasswordPage() {
}, []);
return (
<Box
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 4, borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t("forgotPasswordTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{t("forgotPasswordBody")}
</Typography>
<AuthPageFrame title={t("forgotPasswordTitle")} description={t("forgotPasswordBody")}>
<Box
component="form"
onSubmit={(e) => {
@@ -51,13 +36,17 @@ export default function ForgotPasswordPage() {
const trimmed = email.trim();
if (!trimmed) {
setEmailError(t("emailRequired"));
emailRef.current?.focus();
return;
}
if (!EMAIL_PATTERN.test(trimmed)) {
setEmailError(t("invalidEmail"));
emailRef.current?.focus();
return;
}
setEmailError(undefined);
setSubmitError(null);
setSubmitted(false);
setLoading(true);
api
.post("/auth/request-password-reset", { email: email.trim() })
@@ -66,13 +55,14 @@ export default function ForgotPasswordPage() {
toast(t("passwordResetRequestSent"), "success");
})
.catch((error: any) => {
toast(getApiErrorMessage(error, t("passwordResetRequestFailed")), "error");
setSubmitError(getApiErrorMessage(error, t("passwordResetRequestFailed")));
})
.finally(() => setLoading(false));
}}
sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
>
{submitted ? <Alert severity="success">{t("passwordResetRequestSent")}</Alert> : null}
{submitted ? <Alert severity="success" role="status">{t("passwordResetRequestSent")}</Alert> : null}
{submitError ? <Alert severity="error">{submitError}</Alert> : null}
<TextField
label={t("profileEmail")}
type="email"
@@ -80,21 +70,22 @@ export default function ForgotPasswordPage() {
onChange={(e) => { setEmail(e.target.value); setEmailError(undefined); }}
autoComplete="email"
autoFocus
inputRef={emailRef}
error={Boolean(emailError)}
helperText={emailError}
fullWidth
/>
<Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1, mt: 1 }}>
<Box sx={{ display: "flex", flexWrap: "wrap", justifyContent: "flex-end", gap: 1, mt: 1, "& > button": { maxWidth: "100%", whiteSpace: "normal", overflowWrap: "anywhere" } }}>
<Button type="button" variant="outlined" onClick={() => navigate("/login")} disabled={loading}>
{t("backToLogin")}
</Button>
<Button type="submit" variant="contained" disabled={loading}>
{loading ? t("passwordResetRequestSending") : t("forgotPasswordSubmit")}
<Button type="submit" variant="contained" disabled={loading} aria-busy={loading}>
{t("forgotPasswordSubmit")}
</Button>
</Box>
{loading ? <Typography role="status" aria-live="polite" variant="body2" color="text.secondary">{t("passwordResetRequestSending")}</Typography> : null}
</Box>
</Paper>
</Box>
</AuthPageFrame>
);
}
+39 -33
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from "react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Alert, Box, Button, Checkbox, Divider, FormControlLabel, Paper, TextField, Typography } from "@mui/material";
import { Alert, Box, Button, Checkbox, Divider, FormControlLabel, TextField, Typography } from "@mui/material";
import { useLocation, useNavigate } from "react-router-dom";
@@ -12,6 +12,7 @@ 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;
@@ -31,6 +32,8 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
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("");
@@ -44,6 +47,10 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
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@]+$/;
@@ -56,13 +63,18 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
state: { from: contextPath, ...(Number.isSafeInteger(fromState.focusJobId) && fromState.focusJobId > 0 ? { focusJobId: fromState.focusJobId } : {}) },
} : { replace: true };
useEffect(() => {
api
const loadAuthConfig = useCallback(() => {
setConfigLoading(true);
setConfigFailed(false);
return api
.get<AuthConfig>("/auth/config")
.then((r) => setCfg(r.data))
.catch(() => setCfg(null));
.catch(() => { setCfg(null); setConfigFailed(true); })
.finally(() => setConfigLoading(false));
}, []);
useEffect(() => { void loadAuthConfig(); }, [loadAuthConfig]);
async function completeLogin() {
setAuthPersistencePreference(rememberMe ? "local" : "session");
await api.get("/auth/me");
@@ -83,12 +95,16 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
}
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 {
@@ -109,7 +125,7 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
if (mode === "login" && e?.response?.data?.error === "email_not_verified") {
setEmailNotVerified(true);
} else {
toast(getApiErrorMessage(e, t("loginFailed")), "error");
setSubmitError(getApiErrorMessage(e, t("loginFailed")));
}
} finally {
setLoading(false);
@@ -118,12 +134,13 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
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) {
toast(getApiErrorMessage(e, t("verifyEmailFailed")), "error");
setSubmitError(getApiErrorMessage(e, t("verifyEmailFailed")));
} finally {
setResendingVerification(false);
}
@@ -132,26 +149,11 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
const allowReg = cfg?.allowRegistration ?? false;
return (
<Box
component="main"
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 4, borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
<Typography component="h1" variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{registerMode ? t("createAccount") : t("signInTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{cfg?.requireAuth ? t("authRequired") : t("authOptional")}
</Typography>
<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 ? (
@@ -167,6 +169,7 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
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
@@ -187,15 +190,17 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
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={t("profileCurrentPassword")}
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)}
@@ -207,6 +212,7 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
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}
@@ -251,16 +257,17 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
size="small"
disableRipple
disabled={loading}
onClick={() => { if (initialMode === "register") navigate("/login"); else setRegisterMode((v) => !v); setFieldErrors({}); }}
sx={{ px: 0, minWidth: 0, fontWeight: 700 }}
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)} sx={{ ml: "auto" }}>
<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) ? (
@@ -274,7 +281,6 @@ export default function LoginPage({ initialMode = "login" }: { initialMode?: "lo
) : null}
</>
)}
</Paper>
</Box>
</AuthPageFrame>
);
}
@@ -1,11 +1,12 @@
import React, { useState } from "react";
import { Alert, Box, Button, CircularProgress, Paper, Typography } from "@mui/material";
import { Alert, Box, Button, CircularProgress, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { getMicrosoftMsalInstance } from "../components/MicrosoftAuthCard";
import { useI18n } from "../i18n/I18nProvider";
import AuthPageFrame from "../layout/AuthPageFrame";
export default function MicrosoftLegacyRelinkPage() {
const { t } = useI18n();
@@ -45,22 +46,19 @@ export default function MicrosoftLegacyRelinkPage() {
}
return (
<Box sx={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", p: 2 }}>
<Paper sx={{ width: "min(520px, 100%)", p: 4, borderRadius: 4 }}>
<Typography variant="h5" sx={{ fontWeight: 900 }}>{t("microsoftLegacyRelinkTitle")}</Typography>
<Typography sx={{ color: "text.secondary", mt: 1 }}>{t("microsoftLegacyRelinkBody")}</Typography>
<AuthPageFrame title={t("microsoftLegacyRelinkTitle")} description={t("microsoftLegacyRelinkBody")}>
{missing ? <Alert severity="error" sx={{ mt: 2 }}>{t("microsoftLegacyRelinkMissing")}</Alert> : null}
{error ? <Alert severity="error" sx={{ mt: 2 }}>{error}</Alert> : null}
{success ? <Alert severity="success" sx={{ mt: 2 }}>{t("microsoftLegacyRelinkSuccess")}</Alert> : null}
<Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1, mt: 3 }}>
{success ? <Alert severity="success" role="status" sx={{ mt: 2 }}>{t("microsoftLegacyRelinkSuccess")}</Alert> : null}
<Box sx={{ display: "flex", flexWrap: "wrap", justifyContent: "flex-end", gap: 1, mt: 3, "& > button": { maxWidth: "100%", whiteSpace: "normal", overflowWrap: "anywhere" } }}>
<Button onClick={() => navigate("/login")}>{t("backToLogin")}</Button>
{!success ? (
<Button variant="contained" disabled={missing || working} onClick={() => void confirm()}>
{working ? <CircularProgress size={20} /> : t("continueWithMicrosoft")}
<Button variant="contained" disabled={missing || working} aria-busy={working} startIcon={working ? <CircularProgress size={20} aria-hidden="true" /> : undefined} onClick={() => void confirm()}>
{t("continueWithMicrosoft")}
</Button>
) : null}
</Box>
</Paper>
</Box>
{working ? <Typography role="status" aria-live="polite" variant="body2" color="text.secondary" sx={{ mt: 1.5 }}>{t("loading")}</Typography> : null}
</AuthPageFrame>
);
}
+20 -27
View File
@@ -1,12 +1,13 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import { Alert, Box, Button, Paper, TextField, Typography } from "@mui/material";
import { Alert, Box, Button, TextField, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
import AuthPageFrame from "../layout/AuthPageFrame";
export default function ResetPasswordPage() {
const { toast } = useToast();
@@ -19,6 +20,9 @@ export default function ResetPasswordPage() {
const [confirmPassword, setConfirmPassword] = useState("");
const [loading, setLoading] = useState(false);
const [fieldErrors, setFieldErrors] = useState<{ newPassword?: string; confirmPassword?: string }>({});
const [submitError, setSubmitError] = useState<string | null>(null);
const passwordRef = useRef<HTMLInputElement>(null);
const confirmPasswordRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
@@ -29,25 +33,7 @@ export default function ResetPasswordPage() {
const missingResetInfo = !email || !token;
return (
<Box
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 4, borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t("resetPasswordTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{t("resetPasswordBody")}
</Typography>
<AuthPageFrame title={t("resetPasswordTitle")} description={t("resetPasswordBody")}>
<Box
component="form"
onSubmit={(e) => {
@@ -60,8 +46,12 @@ export default function ResetPasswordPage() {
if (!newPassword || newPassword.length < 8) errors.newPassword = t("passwordTooShort");
if (confirmPassword !== newPassword) errors.confirmPassword = t("passwordsDoNotMatch");
setFieldErrors(errors);
if (Object.keys(errors).length > 0) return;
if (Object.keys(errors).length > 0) {
(errors.newPassword ? passwordRef : confirmPasswordRef).current?.focus();
return;
}
setSubmitError(null);
setLoading(true);
api
.post("/auth/reset-password", { email, token, newPassword })
@@ -70,13 +60,14 @@ export default function ResetPasswordPage() {
navigate("/login", { replace: true });
})
.catch((e2: any) => {
toast(getApiErrorMessage(e2, t("resetFailed")), "error");
setSubmitError(getApiErrorMessage(e2, t("resetFailed")));
})
.finally(() => setLoading(false));
}}
sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
>
{missingResetInfo ? <Alert severity="warning">{t("missingResetLinkInfo")}</Alert> : null}
{submitError ? <Alert severity="error">{submitError}</Alert> : null}
<TextField label={t("profileEmail")} type="email" value={email} onChange={(e) => setEmail(e.target.value)} disabled={!missingResetInfo} fullWidth />
<TextField
label={t("profileNewPassword")}
@@ -84,6 +75,7 @@ export default function ResetPasswordPage() {
value={newPassword}
onChange={(e) => { setNewPassword(e.target.value); setFieldErrors((f) => ({ ...f, newPassword: undefined, confirmPassword: undefined })); }}
autoComplete="new-password"
inputRef={passwordRef}
error={Boolean(fieldErrors.newPassword)}
helperText={fieldErrors.newPassword || t("passwordTooShort")}
fullWidth
@@ -94,21 +86,22 @@ export default function ResetPasswordPage() {
value={confirmPassword}
onChange={(e) => { setConfirmPassword(e.target.value); setFieldErrors((f) => ({ ...f, confirmPassword: undefined })); }}
autoComplete="new-password"
inputRef={confirmPasswordRef}
error={Boolean(fieldErrors.confirmPassword)}
helperText={fieldErrors.confirmPassword}
fullWidth
/>
<Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1, mt: 1 }}>
<Box sx={{ display: "flex", flexWrap: "wrap", justifyContent: "flex-end", gap: 1, mt: 1, "& > button": { maxWidth: "100%", whiteSpace: "normal", overflowWrap: "anywhere" } }}>
<Button type="button" variant="outlined" onClick={() => navigate("/login")} disabled={loading}>
{t("backToLogin")}
</Button>
<Button type="submit" variant="contained" disabled={loading || missingResetInfo}>
<Button type="submit" variant="contained" disabled={loading || missingResetInfo} aria-busy={loading}>
{t("updatePassword")}
</Button>
</Box>
{loading ? <Typography role="status" aria-live="polite" variant="body2" color="text.secondary">{t("saving")}</Typography> : null}
</Box>
</Paper>
</Box>
</AuthPageFrame>
);
}
+9 -24
View File
@@ -1,11 +1,12 @@
import React, { useEffect, useState } from "react";
import { Alert, Box, Button, CircularProgress, Paper, Typography } from "@mui/material";
import { Alert, Box, Button, CircularProgress, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
import AuthPageFrame from "../layout/AuthPageFrame";
type Status = "verifying" | "success" | "error";
@@ -38,39 +39,23 @@ export default function VerifyEmailPage({ emailChange = false }: { emailChange?:
}, [emailChange, t]);
return (
<Box
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 4, borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t(emailChange ? "confirmEmailChangeTitle" : "verifyEmailTitle")}
</Typography>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5, mt: 2 }}>
<AuthPageFrame title={t(emailChange ? "confirmEmailChangeTitle" : "verifyEmailTitle")}>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
{status === "verifying" && (
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<CircularProgress size={20} />
<Box role="status" aria-live="polite" sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<CircularProgress size={20} aria-hidden="true" />
<Typography sx={{ color: "text.secondary" }}>{t(emailChange ? "confirmEmailChangeVerifying" : "verifyEmailVerifying")}</Typography>
</Box>
)}
{status === "success" && <Alert severity="success">{t(emailChange ? "confirmEmailChangeSuccess" : "verifyEmailSuccess")}</Alert>}
{status === "success" && <Alert severity="success" role="status">{t(emailChange ? "confirmEmailChangeSuccess" : "verifyEmailSuccess")}</Alert>}
{status === "error" && <Alert severity="error">{errorMessage}</Alert>}
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 1 }}>
<Box sx={{ display: "flex", flexWrap: "wrap", justifyContent: "flex-end", mt: 1, "& > button": { maxWidth: "100%", whiteSpace: "normal", overflowWrap: "anywhere" } }}>
<Button variant="contained" onClick={() => navigate("/login")}>
{t("backToLogin")}
</Button>
</Box>
</Box>
</Paper>
</Box>
</AuthPageFrame>
);
}