feat(registration): add email confirmation UI
Build, Test & Push Frontend / quality-check (push) Successful in 26s
Build, Test & Push Frontend / docker (push) Successful in 31s

New ConfirmEmailPage for users to verify their email and set password.
Resend form on registration and error pages. Registration form no
longer asks for a password. Confirmation requires a button click. The
admin list marks unconfirmed requests and offers only delete for them.
This commit is contained in:
lobo committed 2026-10-01 16:20:51 +02:00
1 parent 249973dd69
commit 6dda186bdf
15 files changed
+416 -50

No files matched your search

+18 -4
View File
@@ -18,7 +18,7 @@ import {
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import PageContainer from '../components/PageContainer.jsx';
import {decideUser, deleteUser, fetchUsers, setUserBlocked} from '../utils/admin.js';
import {decideUser, deleteUnconfirmedUser, deleteUser, fetchUsers, setUserBlocked} from '../utils/admin.js';
import {formatDate} from '../utils/format.js';
import useAbortPrevious from '../hooks/useAbortPrevious.js';
@@ -29,12 +29,14 @@ const REFUSAL_KEY = {
ALREADY_DELETED: 'ADMIN.ERROR_ALREADY_DELETED',
NOT_PENDING: 'ADMIN.ERROR_NOT_PENDING',
TARGET_IS_PENDING: 'ADMIN.ERROR_TARGET_IS_PENDING',
TARGET_IS_UNCONFIRMED: 'ADMIN.ERROR_TARGET_IS_UNCONFIRMED',
NOT_UNCONFIRMED: 'ADMIN.ERROR_NOT_UNCONFIRMED',
};
const formatDateOrNull = (value, locale) => (value ? formatDate(value, locale) : null);
/**
* PLATFORM_ADMIN only: list, block and delete users, accept or deny registrations that wait. Auth checks the role; a
* PLATFORM_ADMIN only: list, block and delete users, accept or deny registrations that wait, delete the ones whose address is not confirmed. Auth checks the role; a
* 403 shows "no access".
*/
export default function AdminUsersPage() {
@@ -45,7 +47,7 @@ export default function AdminUsersPage() {
const [pendingOnly, setPendingOnly] = useState(false);
const [result, setResult] = useState(null);
const [status, setStatus] = useState('loading');
// {kind: 'block' | 'delete' | 'accept' | 'deny', user}
// {kind: 'block' | 'delete' | 'deleteUnconfirmed' | 'accept' | 'deny', user}
const [pending, setPending] = useState(null);
const [typedEmail, setTypedEmail] = useState('');
const [busy, setBusy] = useState(false);
@@ -92,6 +94,11 @@ export default function AdminUsersPage() {
title: t('ADMIN.DELETE_TITLE', {email}), text: t('ADMIN.DELETE_TEXT'), action: 'ADMIN.DELETE',
done: 'ADMIN.DONE_DELETE', destructive: true, run: () => deleteUser(pending.user.id),
},
deleteUnconfirmed: {
title: t('ADMIN.DELETE_UNCONFIRMED_TITLE', {email}), text: t('ADMIN.DELETE_UNCONFIRMED_TEXT'),
action: 'ADMIN.DELETE', done: 'ADMIN.DONE_DELETE', destructive: true,
run: () => deleteUnconfirmedUser(pending.user.id),
},
block: {
...(pending.user.blocked
? {title: t('ADMIN.UNBLOCK'), text: email, action: 'ADMIN.UNBLOCK', done: 'ADMIN.DONE_UNBLOCK'}
@@ -181,6 +188,7 @@ export default function AdminUsersPage() {
<div className="flex flex-wrap items-center gap-1">
{user.role !== 'USER' && <Badge variant="outline">{t(`ROLES.${user.role}`)}</Badge>}
{user.steamLinked && <Badge variant="secondary">{t('ADMIN.STEAM')}</Badge>}
{user.status === 'UNCONFIRMED' && <Badge variant="outline">{t('ADMIN.UNCONFIRMED')}</Badge>}
{user.status === 'PENDING' && <Badge>{t('ADMIN.PENDING')}</Badge>}
{user.blocked && <Badge variant="destructive">{t('ADMIN.BLOCKED')}</Badge>}
{user.deletedAt && (
@@ -189,6 +197,12 @@ export default function AdminUsersPage() {
</Badge>
)}
</div>
{user.status === 'UNCONFIRMED' && (
<Button type="button" variant="outline" size="sm" className="border-destructive text-destructive"
onClick={() => setPending({kind: 'deleteUnconfirmed', user})}>
<Trash2/>{t('ADMIN.DELETE')}
</Button>
)}
{user.status === 'PENDING' && (
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm"
@@ -201,7 +215,7 @@ export default function AdminUsersPage() {
</Button>
</div>
)}
{user.role !== 'PLATFORM_ADMIN' && !user.deletedAt && user.status !== 'PENDING' && (
{user.role !== 'PLATFORM_ADMIN' && !user.deletedAt && user.status !== 'PENDING' && user.status !== 'UNCONFIRMED' && (
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm"
onClick={() => setPending({kind: 'block', user})}>
+19
View File
@@ -15,6 +15,7 @@ const PLAYER = {
lastLoginDate: null, steamLinked: true, blocked: false, deletedAt: null, status: 'ACTIVE',
};
const NEWCOMER = {...PLAYER, id: 8, email: 'new@example.com', steamLinked: false, status: 'PENDING'};
const UNCONFIRMED = {...PLAYER, id: 10, email: 'unconfirmed@example.com', steamLinked: false, status: 'UNCONFIRMED'};
const DENIED = {...PLAYER, id: 9, email: 'denied@example.com', steamLinked: false, status: 'DENIED',
deletedAt: '2026-10-01T10:00:00Z'};
const ADMIN = {...PLAYER, id: 1, email: 'admin@example.com', role: 'PLATFORM_ADMIN', steamLinked: false};
@@ -139,6 +140,24 @@ describe('AdminUsersPage', () => {
await waitFor(() => expect(calls('GET').at(-1)[0]).toContain('status=PENDING&page=0'));
});
it('marks an unconfirmed request, offers no accept and deletes it hard after the confirm', async () => {
withRoutes({
'GET /api/admin/users': json(200, page([UNCONFIRMED])),
'DELETE /api/admin/users/10/unconfirmed': json(204),
});
renderPage();
expect(await screen.findByText('ADMIN.UNCONFIRMED')).toBeTruthy();
expect(screen.queryByRole('button', {name: 'ADMIN.ACCEPT'})).toBeNull();
expect(screen.queryByRole('button', {name: 'ADMIN.DENY'})).toBeNull();
expect(screen.queryByRole('button', {name: 'ADMIN.BLOCK'})).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'ADMIN.DELETE'}));
fireEvent.click(screen.getAllByRole('button', {name: 'ADMIN.DELETE'}).at(-1));
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('ADMIN.DONE_DELETE'));
expect(calls('DELETE')[0][0]).toMatch(/\/api\/admin\/users\/10\/unconfirmed$/);
});
it('says no access to a user without the admin role', async () => {
withRoutes({'GET /api/admin/users': json(403, {})});
renderPage();
+100
View File
@@ -0,0 +1,100 @@
import {useState} from 'react';
import {Link, useLocation} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {useForm} from 'react-hook-form';
import {zodResolver} from '@hookform/resolvers/zod';
import {Loader2} from 'lucide-react';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import AuthLayout from '../components/AuthLayout.jsx';
import FeedbackAlert from '../components/FeedbackAlert.jsx';
import FormField from '../components/FormField.jsx';
import ResendConfirmation from '../components/ResendConfirmation.jsx';
import {confirmEmailSchema} from '../utils/validation.js';
import {clientFetch} from '../utils/api.js';
/**
* The link of the confirmation mail. The token is in the fragment, so no server log sees it. It is sent only on the
* click: a mail scanner that opens the link must not use it up. The owner of the address chooses the password here.
*/
export default function ConfirmEmailPage() {
const token = useLocation().hash.slice(1);
// A new link in the same tab only changes the fragment: key restarts the state.
return <ConfirmEmail key={token} token={token}/>;
}
function ConfirmEmail({token}) {
const {t} = useTranslation();
const [state, setState] = useState(token ? 'idle' : 'invalid');
const {register, handleSubmit, formState: {errors, isSubmitting}} = useForm({
resolver: zodResolver(confirmEmailSchema),
defaultValues: {password: '', passwordConfirmation: ''},
});
const [error, setError] = useState('');
const confirm = async ({password}) => {
setError('');
try {
const response = await clientFetch(`${import.meta.env.VITE_API_URL}/api/registration/confirm`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({token, password}),
});
if (response.ok) {
setState('done');
} else if (response.status === 410 || response.status === 400) {
setState('invalid');
} else if (response.status === 429) {
const minutes = Math.ceil(Number(response.headers.get('Retry-After') ?? 900) / 60);
setError(t('REGISTRATION.ERROR_TOO_MANY_ATTEMPTS', {minutes}));
} else {
setError(t('REGISTRATION.ERROR_GENERIC'));
}
} catch (err) {
console.error('Confirm API error:', err);
setError(t('INFO.ERROR.NETWORK_FAILURE'));
}
};
return (
<AuthLayout title={t('CONFIRM_EMAIL.TITLE')}>
{state === 'idle' && <form onSubmit={handleSubmit(confirm)} className="space-y-4" noValidate>
<p className="text-sm text-muted-foreground">{t('CONFIRM_EMAIL.INTRO')}</p>
<FormField id="password" label={t('REGISTRATION.PASSWORD')} error={errors.password} t={t}>
<Input
id="password"
type="password"
autoComplete="new-password"
aria-invalid={!!errors.password}
{...register('password')}
/>
</FormField>
<FormField id="passwordConfirmation" label={t('REGISTRATION.PASSWORD_CONFIRMATION')} error={errors.passwordConfirmation} t={t}>
<Input
id="passwordConfirmation"
type="password"
autoComplete="new-password"
aria-invalid={!!errors.passwordConfirmation}
{...register('passwordConfirmation')}
/>
</FormField>
<Button type="submit" disabled={isSubmitting} className="w-full">
{isSubmitting && <Loader2 className="animate-spin"/>}
{t('CONFIRM_EMAIL.SUBMIT')}
</Button>
<FeedbackAlert message={error} isError/>
</form>}
{state === 'done' && <>
<FeedbackAlert message={t('CONFIRM_EMAIL.DONE')} isError={false}/>
<Link to="/login" className="block text-center text-sm font-medium text-primary hover:underline">
{t('CONFIRM_EMAIL.TO_LOGIN')}
</Link>
</>}
{state === 'invalid' && <>
<FeedbackAlert message={t('CONFIRM_EMAIL.INVALID')} isError/>
<ResendConfirmation/>
</>}
</AuthLayout>
);
}
+80
View File
@@ -0,0 +1,80 @@
// @vitest-environment jsdom
import {afterEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen} from '@testing-library/react';
import {Link, MemoryRouter, Route, Routes} from 'react-router-dom';
import ConfirmEmailPage from './ConfirmEmailPage.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
const renderPage = (hash) => render(
<MemoryRouter initialEntries={[`/confirm-email${hash}`]}><ConfirmEmailPage/></MemoryRouter>,
);
function submitPasswords(password, repeat = password) {
fireEvent.change(screen.getByLabelText('REGISTRATION.PASSWORD'), {target: {value: password}});
fireEvent.change(screen.getByLabelText('REGISTRATION.PASSWORD_CONFIRMATION'), {target: {value: repeat}});
fireEvent.click(screen.getByRole('button', {name: 'CONFIRM_EMAIL.SUBMIT'}));
}
describe('ConfirmEmailPage', () => {
afterEach(cleanup);
it('sends the fragment token and the chosen password only on the click and then says it is confirmed', async () => {
const mock = fetchRoutes({'POST /api/registration/confirm': json(204, null)});
renderPage('#tok-123');
expect(mock).not.toHaveBeenCalled();
submitPasswords('secret123');
expect(await screen.findByText('CONFIRM_EMAIL.DONE')).toBeTruthy();
expect(JSON.parse(mock.mock.calls[0][1].body)).toEqual({token: 'tok-123', password: 'secret123'});
});
it.each([
['a short password', 'short', 'short', 'VALIDATION.PASSWORD_TOO_SHORT'],
['a different repeat', 'secret123', 'secret124', 'VALIDATION.PASSWORD_MISMATCH'],
])('sends nothing for %s', async (_name, password, repeat, message) => {
const mock = fetchRoutes({});
renderPage('#tok-123');
submitPasswords(password, repeat);
expect(await screen.findByText(message)).toBeTruthy();
expect(mock).not.toHaveBeenCalled();
});
it('shows the invalid text and the resend form for a used or expired link', async () => {
fetchRoutes({'POST /api/registration/confirm': json(410, {code: 'CONFIRMATION_INVALID'})});
renderPage('#old');
submitPasswords('secret123');
expect(await screen.findByText('CONFIRM_EMAIL.INVALID')).toBeTruthy();
expect(screen.getByRole('button', {name: 'REGISTRATION.RESEND'})).toBeTruthy();
});
it('a new link in the same tab shows the password form again', async () => {
fetchRoutes({'POST /api/registration/confirm': json(410, {code: 'CONFIRMATION_INVALID'})});
render(
<MemoryRouter initialEntries={['/confirm-email#old']}>
<Routes><Route path="/confirm-email" element={<ConfirmEmailPage/>}/></Routes>
<Link to="/confirm-email#new">open the new link</Link>
</MemoryRouter>,
);
submitPasswords('secret123');
expect(await screen.findByText('CONFIRM_EMAIL.INVALID')).toBeTruthy();
fireEvent.click(screen.getByText('open the new link'));
expect(screen.getByLabelText('REGISTRATION.PASSWORD')).toBeTruthy();
});
it('is invalid at once without a token and sends no request', () => {
const mock = fetchRoutes({});
renderPage('');
expect(screen.getByText('CONFIRM_EMAIL.INVALID')).toBeTruthy();
expect(mock).not.toHaveBeenCalled();
});
});
+6 -27
View File
@@ -11,6 +11,7 @@ import {Input} from '@/components/ui/input';
import AuthLayout from '../components/AuthLayout.jsx';
import FeedbackAlert from '../components/FeedbackAlert.jsx';
import FormField from '../components/FormField.jsx';
import ResendConfirmation from '../components/ResendConfirmation.jsx';
import {registrationSchema} from '../utils/validation.js';
import {clientFetch} from '../utils/api.js';
import {MAX_DISPLAY_NAME_LENGTH} from '../utils/limits.js';
@@ -25,8 +26,8 @@ const BACKEND_ERROR_KEY = {
export default function RegistrationPage() {
const {t} = useTranslation();
const [feedback, setFeedback] = useState({message: '', isError: false});
// The request waits for the admin; a second one would only be refused.
const [requested, setRequested] = useState(false);
// Set once sent: the request waits for the confirmation, a second one would only be refused.
const [requestedEmail, setRequestedEmail] = useState(null);
const {
register,
@@ -36,8 +37,6 @@ export default function RegistrationPage() {
resolver: zodResolver(registrationSchema),
defaultValues: {
email: '',
password: '',
passwordConfirmation: '',
displayName: '',
},
});
@@ -51,7 +50,6 @@ export default function RegistrationPage() {
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: values.email,
password: values.password,
displayName: values.displayName,
// Auth's mails use it: a German browser gets German, every other one English.
language: navigator.language?.toLowerCase().startsWith('de') ? 'de' : 'en',
@@ -60,7 +58,7 @@ export default function RegistrationPage() {
if (response.ok) {
setFeedback({message: t('REGISTRATION.SUCCESS'), isError: false});
setRequested(true);
setRequestedEmail(values.email);
return;
}
@@ -90,7 +88,7 @@ export default function RegistrationPage() {
</>}
>
<p className="mb-4 text-sm text-muted-foreground">{t('REGISTRATION.INTRO')}</p>
{!requested && <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
{requestedEmail === null && <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
<FormField id="email" label={t('REGISTRATION.EMAIL')} error={errors.email} t={t}>
<Input
id="email"
@@ -101,26 +99,6 @@ export default function RegistrationPage() {
/>
</FormField>
<FormField id="password" label={t('REGISTRATION.PASSWORD')} error={errors.password} t={t}>
<Input
id="password"
type="password"
autoComplete="new-password"
aria-invalid={!!errors.password}
{...register('password')}
/>
</FormField>
<FormField id="passwordConfirmation" label={t('REGISTRATION.PASSWORD_CONFIRMATION')} error={errors.passwordConfirmation} t={t}>
<Input
id="passwordConfirmation"
type="password"
autoComplete="new-password"
aria-invalid={!!errors.passwordConfirmation}
{...register('passwordConfirmation')}
/>
</FormField>
<FormField id="displayName" label={t('REGISTRATION.DISPLAY_NAME')} error={errors.displayName} t={t}>
<Input
id="displayName"
@@ -138,6 +116,7 @@ export default function RegistrationPage() {
</form>}
<FeedbackAlert message={feedback.message} isError={feedback.isError}/>
{requestedEmail !== null && <ResendConfirmation defaultEmail={requestedEmail}/>}
</AuthLayout>
);
}
+20 -2
View File
@@ -21,8 +21,6 @@ const answerRegistration = (status, code, headers = {}, message = undefined) =>
function submitValidForm() {
render(<MemoryRouter><RegistrationPage/></MemoryRouter>);
fireEvent.change(screen.getByLabelText('REGISTRATION.EMAIL'), {target: {value: 'a@b.de'}});
fireEvent.change(screen.getByLabelText('REGISTRATION.PASSWORD'), {target: {value: 'secret123'}});
fireEvent.change(screen.getByLabelText('REGISTRATION.PASSWORD_CONFIRMATION'), {target: {value: 'secret123'}});
fireEvent.click(screen.getByRole('button', {name: 'REGISTRATION.SUBMIT'}));
}
@@ -40,6 +38,26 @@ describe('RegistrationPage', () => {
expect(await screen.findByText('REGISTRATION.ERROR_TOO_MANY_ATTEMPTS:15')).toBeTruthy();
});
it('shows the resend form with the typed address after a successful send', async () => {
fetchRoutes({'POST /api/registration/new': json(200, {userId: 1})});
submitValidForm();
expect(await screen.findByText('REGISTRATION.SUCCESS')).toBeTruthy();
expect(screen.getByLabelText('REGISTRATION.RESEND_EMAIL').value).toBe('a@b.de');
});
it('asks for no password and sends none: the address owner chooses it when confirming', async () => {
answerRegistration(409, 'EMAIL_ALREADY_IN_USE');
submitValidForm();
await screen.findByText('REGISTRATION.ERROR_EMAIL_IN_USE');
expect(screen.queryByLabelText('REGISTRATION.PASSWORD')).toBeNull();
expect(screen.queryByLabelText('REGISTRATION.PASSWORD_CONFIRMATION')).toBeNull();
expect(JSON.parse(fetch.mock.calls[0][1].body)).not.toHaveProperty('password');
});
it('asks for no Steam ID and sends none', async () => {
answerRegistration(409, 'EMAIL_ALREADY_IN_USE');