feat(auth): add configurable email verification enforcement

Auth:RequireEmailVerification (default off) gates whether local
register requires confirming email before login. OAuth new-user paths
are untouched -- Google/Microsoft already assert a verified email.
Adds verify-email and resend-verification-email endpoints, mirroring
the existing reset-password enumeration-avoidance and rate-limiting
patterns, plus a login-embedded resend affordance and a verify-email
landing page on the frontend.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
cesnimda
2026-07-13 01:22:26 +02:00
parent 0ca2f2b261
commit 904f3a8ec8
9 changed files with 528 additions and 3 deletions
+2
View File
@@ -31,6 +31,7 @@ import LoginPage from "./views/LoginPage";
import LandingPage from "./views/LandingPage";
import ForgotPasswordPage from "./views/ForgotPasswordPage";
import ResetPasswordPage from "./views/ResetPasswordPage";
import VerifyEmailPage from "./views/VerifyEmailPage";
import RouteErrorPage from "./views/RouteErrorPage";
import { api } from "./api";
import { resolveCaptureUrl } from "./captureUrl";
@@ -366,6 +367,7 @@ export default function App() {
{ path: "/login", element: <LoginPage />, errorElement: <RouteErrorPage /> },
{ path: "/forgot-password", element: <ForgotPasswordPage />, errorElement: <RouteErrorPage /> },
{ path: "/reset-password", element: <ResetPasswordPage />, errorElement: <RouteErrorPage /> },
{ path: "/verify-email", element: <VerifyEmailPage />, errorElement: <RouteErrorPage /> },
{ path: "/*", element: <Shell jobPageSize={jobPageSize} setJobPageSize={setJobPageSize} jobColumns={jobColumns} setJobColumns={setJobColumns} themeMode={themeMode} onThemeModeChange={onThemeModeChange} />, errorElement: <RouteErrorPage /> },
], { future: { v7_relativeSplatPath: true } }), [jobColumns, jobPageSize, themeMode]);
+18
View File
@@ -764,6 +764,15 @@ export const translations = {
resetFailed: "Reset failed.",
backToLogin: "Back to login",
updatePassword: "Update password",
emailNotVerified: "Please verify your email address before signing in.",
resendVerificationEmail: "Resend verification email",
verificationEmailResent: "Verification email sent. Check your inbox.",
registerCheckEmailForVerification: "Check your email to verify your account.",
verifyEmailTitle: "Verify your email",
verifyEmailVerifying: "Verifying your email...",
verifyEmailSuccess: "Your email has been verified. You can now sign in.",
verifyEmailFailed: "This verification link is invalid or has expired.",
missingVerifyLinkInfo: "Missing user/token in link.",
jobTableSearch: "Search",
jobTableSearchPlaceholder: "Title, company, notes, messages",
jobTableStatus: "Status",
@@ -1792,6 +1801,15 @@ export const translations = {
resetFailed: "Tilbakestilling mislyktes.",
backToLogin: "Tilbake til innlogging",
updatePassword: "Oppdater passord",
emailNotVerified: "Vennligst bekreft e-postadressen din før du logger inn.",
resendVerificationEmail: "Send bekreftelses-e-post på nytt",
verificationEmailResent: "Bekreftelses-e-post sendt. Sjekk innboksen din.",
registerCheckEmailForVerification: "Sjekk e-posten din for å bekrefte kontoen.",
verifyEmailTitle: "Bekreft e-posten din",
verifyEmailVerifying: "Bekrefter e-posten din...",
verifyEmailSuccess: "E-posten din er bekreftet. Du kan nå logge inn.",
verifyEmailFailed: "Denne bekreftelseslenken er ugyldig eller har utløpt.",
missingVerifyLinkInfo: "Mangler bruker/token i lenken.",
jobTableSearch: "Søk",
jobTableSearchPlaceholder: "Tittel, selskap, notater, meldinger",
jobTableStatus: "Status",
+29
View File
@@ -137,4 +137,33 @@ describe('LoginPage', () => {
expect(await screen.findByRole('alert')).toHaveTextContent('Too many attempts. Please wait a few minutes and try again.');
});
it('offers a resend-verification action when login reports the account is not verified', async () => {
mockedApi.get.mockResolvedValueOnce({
data: { requireAuth: false, googleEnabled: false, microsoftEnabled: false, localEnabled: true, allowRegistration: false, requireEmailVerification: true },
} as any);
mockedApi.post.mockImplementation((url: string) => {
if (url === '/auth/login') {
return Promise.reject({ response: { status: 403, data: { error: 'email_not_verified' } } });
}
if (url === '/auth/resend-verification-email') {
return Promise.resolve({ data: {} } as any);
}
return Promise.resolve({ data: {} } as any);
});
renderLoginPage();
await screen.findByLabelText('Email');
await userEvent.type(screen.getByLabelText('Email'), 'unverified@example.com');
await userEvent.type(screen.getByLabelText('Current password'), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }));
expect(await screen.findByText('Please verify your email address before signing in.')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Resend verification email' }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith('/auth/resend-verification-email', { email: 'unverified@example.com' }));
await screen.findByText('Verification email sent. Check your inbox.');
});
});
@@ -0,0 +1,58 @@
import React from 'react';
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import VerifyEmailPage from './views/VerifyEmailPage';
import { I18nProvider } from './i18n/I18nProvider';
import { api, getApiErrorMessage } from './api';
const mockedApi = api as jest.Mocked<typeof api>;
// CRA's jest config sets resetMocks: true, which wipes the initial implementation given to
// jest.fn() in setupTests.ts before every test -- re-arm it here so error-derived text is testable.
const mockedGetApiErrorMessage = getApiErrorMessage as jest.Mock;
function renderVerifyEmailPage(search: string) {
window.history.pushState({}, '', `/verify-email${search}`);
return render(
<MemoryRouter initialEntries={[`/verify-email${search}`]} future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
<I18nProvider>
<VerifyEmailPage />
</I18nProvider>
</MemoryRouter>,
);
}
describe('VerifyEmailPage', () => {
beforeEach(() => {
mockedApi.post.mockReset();
mockedGetApiErrorMessage.mockImplementation((e: any, fallback?: string) => {
const data = e?.response?.data;
return typeof data === 'string' && data.trim() ? data.trim() : fallback;
});
});
it('confirms the account and shows success when the link is valid', async () => {
mockedApi.post.mockResolvedValueOnce({ data: {} } as any);
renderVerifyEmailPage('?userId=user-1&token=good-token');
expect(await screen.findByText('Your email has been verified. You can now sign in.')).toBeInTheDocument();
expect(mockedApi.post).toHaveBeenCalledWith('/auth/verify-email', { userId: 'user-1', token: 'good-token' });
});
it('shows an error when the link is invalid or expired', async () => {
mockedApi.post.mockRejectedValueOnce({ response: { status: 400, data: 'Invalid or expired link.' } });
renderVerifyEmailPage('?userId=user-1&token=bad-token');
expect(await screen.findByText('Invalid or expired link.')).toBeInTheDocument();
});
it('shows an error without calling the API when the link is missing userId/token', async () => {
renderVerifyEmailPage('');
expect(await screen.findByText('Missing user/token in link.')).toBeInTheDocument();
expect(mockedApi.post).not.toHaveBeenCalled();
});
});
+40 -2
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from "react";
import { Box, Button, Checkbox, FormControlLabel, Paper, Tab, Tabs, TextField, Typography } from "@mui/material";
import { Alert, Box, Button, Checkbox, FormControlLabel, Paper, Tab, Tabs, TextField, Typography } from "@mui/material";
import { useLocation, useNavigate } from "react-router-dom";
@@ -18,6 +18,7 @@ type AuthConfig = {
microsoftEnabled: boolean;
localEnabled: boolean;
allowRegistration: boolean;
requireEmailVerification: boolean;
};
export default function LoginPage() {
@@ -34,6 +35,9 @@ export default function LoginPage() {
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 nextPath = (location?.state?.from as string | undefined) ?? "/dashboard";
@@ -53,6 +57,8 @@ export default function LoginPage() {
async function submit(mode: "login" | "register") {
setLoading(true);
setEmailNotVerified(false);
setVerificationResent(false);
try {
const url = mode === "register" ? "/auth/register" : "/auth/login";
const res = await api.post<{ requiresTwoFactor?: boolean; pendingToken?: string }>(url, { email, password, rememberMe });
@@ -61,13 +67,33 @@ export default function LoginPage() {
return;
}
await completeLogin();
if (mode === "register" && cfg?.requireEmailVerification) {
toast(t("registerCheckEmailForVerification"), "info");
}
} catch (e: any) {
toast(getApiErrorMessage(e, t("loginFailed")), "error");
if (mode === "login" && e?.response?.data?.error === "email_not_verified") {
setEmailNotVerified(true);
} else {
toast(getApiErrorMessage(e, t("loginFailed")), "error");
}
} finally {
setLoading(false);
}
}
async function resendVerification() {
setResendingVerification(true);
try {
await api.post("/auth/resend-verification-email", { email });
setVerificationResent(true);
toast(t("verificationEmailResent"), "success");
} catch (e: any) {
toast(getApiErrorMessage(e, t("verifyEmailFailed")), "error");
} finally {
setResendingVerification(false);
}
}
const allowReg = cfg?.allowRegistration ?? false;
return (
@@ -106,6 +132,18 @@ export default function LoginPage() {
{tab === 0 && (
<Box component="form" onSubmit={(e) => { e.preventDefault(); void submit("login"); }} sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
{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={t("profileEmail")} value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" fullWidth />
<TextField label={t("profileCurrentPassword")} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete={allowReg ? "new-password" : "current-password"} type="password" fullWidth />
@@ -0,0 +1,75 @@
import React, { useEffect, useState } from "react";
import { Alert, Box, Button, CircularProgress, Paper, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
type Status = "verifying" | "success" | "error";
export default function VerifyEmailPage() {
const { t } = useI18n();
const navigate = useNavigate();
const [status, setStatus] = useState<Status>("verifying");
const [errorMessage, setErrorMessage] = useState<string | null>(null);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const userId = params.get("userId") || "";
const token = params.get("token") || "";
if (!userId || !token) {
setStatus("error");
setErrorMessage(t("missingVerifyLinkInfo"));
return;
}
api
.post("/auth/verify-email", { userId, token })
.then(() => setStatus("success"))
.catch((e: any) => {
setStatus("error");
setErrorMessage(getApiErrorMessage(e, t("verifyEmailFailed")));
});
}, [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: 3 }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t("verifyEmailTitle")}
</Typography>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5, mt: 2 }}>
{status === "verifying" && (
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<CircularProgress size={20} />
<Typography sx={{ color: "text.secondary" }}>{t("verifyEmailVerifying")}</Typography>
</Box>
)}
{status === "success" && <Alert severity="success">{t("verifyEmailSuccess")}</Alert>}
{status === "error" && <Alert severity="error">{errorMessage}</Alert>}
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 1 }}>
<Button variant="contained" onClick={() => navigate("/login")}>
{t("backToLogin")}
</Button>
</Box>
</Box>
</Paper>
</Box>
);
}