feat(admin): add the admin users page and view as
Build, Test & Push Frontend / quality-check (push) Successful in 17s
Build, Test & Push Frontend / docker (push) Successful in 28s

This commit is contained in:
lobo committed 2026-09-27 12:18:10 +02:00
1 parent 46587dfb5c
commit afe00ceae9
14 files changed
+649 -8

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
import {useCallback, useEffect, useRef, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {Ban, ChevronLeft, ChevronRight, Loader2, Search, ShieldCheck, Trash2} from 'lucide-react';
import {toast} from 'sonner';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import PageContainer from '../components/PageContainer.jsx';
import useSessionExpired from '../hooks/useSessionExpired.js';
import {deleteUser, fetchUsers, setUserBlocked} from '../utils/admin.js';
import {hasSession} from '../utils/auth.js';
const PAGE_SIZE = 20;
const REFUSAL_KEY = {
SELF_ACTION: 'ADMIN.ERROR_SELF_ACTION',
TARGET_IS_ADMIN: 'ADMIN.ERROR_TARGET_IS_ADMIN',
ALREADY_DELETED: 'ADMIN.ERROR_ALREADY_DELETED',
};
const formatDate = (value, locale) => (value ? new Date(value).toLocaleDateString(locale) : null);
/**
* PLATFORM_ADMIN only: list, block and delete users. Auth checks the role; a 403 shows "no access".
*/
export default function AdminUsersPage() {
const {t, i18n} = useTranslation();
const navigate = useNavigate();
const expireSession = useSessionExpired();
const [query, setQuery] = useState('');
const [search, setSearch] = useState('');
const [page, setPage] = useState(0);
const [result, setResult] = useState(null);
const [status, setStatus] = useState('loading');
// {kind: 'block' | 'delete', user}
const [pending, setPending] = useState(null);
const [typedEmail, setTypedEmail] = useState('');
const [busy, setBusy] = useState(false);
// Only the newest load may show its answer: a slow answer to an older search must not replace the list.
const loadCount = useRef(0);
const load = useCallback(async () => {
const current = ++loadCount.current;
try {
const response = await fetchUsers(search, page, PAGE_SIZE);
if (current !== loadCount.current) return;
if (response.status === 401) {
expireSession();
return;
}
if (response.status === 403) {
setStatus('forbidden');
return;
}
if (!response.ok) {
setStatus('error');
return;
}
const data = await response.json();
if (current !== loadCount.current) return;
setResult(data);
setStatus('ready');
} catch (err) {
console.error('Admin users error:', err);
setStatus('error');
}
}, [search, page, expireSession]);
useEffect(() => {
if (!hasSession()) {
navigate('/login');
return;
}
load();
}, [load, navigate]);
const closeDialog = () => {
setPending(null);
setTypedEmail('');
};
const confirm = async () => {
const {kind, user} = pending;
setBusy(true);
try {
const response = kind === 'delete' ? await deleteUser(user.id) : await setUserBlocked(user.id, !user.blocked);
if (response.status === 401) {
expireSession();
return;
}
if (response.ok) {
toast.success(t(kind === 'delete' ? 'ADMIN.DONE_DELETE' : user.blocked ? 'ADMIN.DONE_UNBLOCK' : 'ADMIN.DONE_BLOCK'));
closeDialog();
await load();
} else {
const data = await response.json().catch(() => ({}));
toast.error(t(REFUSAL_KEY[data.code] ?? 'ADMIN.ERROR'));
}
} catch (err) {
console.error('Admin action error:', err);
toast.error(t('INFO.ERROR.NETWORK_FAILURE'));
} finally {
setBusy(false);
}
};
const submitSearch = (event) => {
event.preventDefault();
setPage(0);
setSearch(query.trim());
};
const confirmDisabled = busy || (pending?.kind === 'delete'
&& typedEmail.trim().toLowerCase() !== pending.user.email.toLowerCase());
return (
<PageContainer className="space-y-4 px-4 py-6 md:px-8">
<Card>
<CardHeader>
<CardTitle>{t('ADMIN.TITLE')}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{status === 'forbidden' && <p className="text-sm text-muted-foreground">{t('ADMIN.NO_ACCESS')}</p>}
{status === 'error' && <p className="text-sm text-destructive">{t('ADMIN.LOAD_ERROR')}</p>}
{status !== 'forbidden' && (
<form onSubmit={submitSearch} className="flex gap-2">
<Input aria-label={t('ADMIN.SEARCH')} placeholder={t('ADMIN.SEARCH')} value={query}
onChange={(event) => setQuery(event.target.value)}/>
<Button type="submit" variant="outline" size="icon" aria-label={t('ADMIN.SEARCH')}><Search/></Button>
</form>
)}
{status === 'loading' && <Loader2 className="size-5 animate-spin text-muted-foreground"/>}
{status === 'ready' && result.content.length === 0 && (
<p className="text-sm text-muted-foreground">{t('ADMIN.EMPTY')}</p>
)}
{status === 'ready' && result.content.length > 0 && (
<ul className="divide-y">
{result.content.map((user) => (
<li key={user.id} className="flex flex-wrap items-center gap-3 py-3">
<div className="min-w-0 flex-1">
<p className="truncate font-medium">{user.email}</p>
<p className="truncate text-xs text-muted-foreground">
{[user.displayName,
t('ADMIN.REGISTERED', {date: formatDate(user.registrationDate, i18n.language)}),
t('ADMIN.LAST_LOGIN', {date: formatDate(user.lastLoginDate, i18n.language) ?? t('ADMIN.NEVER')}),
].filter(Boolean).join(' · ')}
</p>
</div>
<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.blocked && <Badge variant="destructive">{t('ADMIN.BLOCKED')}</Badge>}
{user.deletedAt && <Badge variant="destructive">{t('ADMIN.DELETED')}</Badge>}
</div>
{user.role !== 'PLATFORM_ADMIN' && !user.deletedAt && (
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm"
onClick={() => setPending({kind: 'block', user})}>
{user.blocked ? <ShieldCheck/> : <Ban/>}
{t(user.blocked ? 'ADMIN.UNBLOCK' : 'ADMIN.BLOCK')}
</Button>
<Button type="button" variant="outline" size="sm" className="border-destructive text-destructive"
onClick={() => setPending({kind: 'delete', user})}>
<Trash2/>{t('ADMIN.DELETE')}
</Button>
</div>
)}
</li>
))}
</ul>
)}
{status === 'ready' && result.totalPages > 1 && (
<div className="flex items-center justify-between gap-2 text-sm">
<Button type="button" variant="outline" size="sm" disabled={page === 0}
onClick={() => setPage(page - 1)}>
<ChevronLeft/>{t('ADMIN.PREVIOUS')}
</Button>
<span>{t('ADMIN.PAGE_OF', {current: page + 1, total: result.totalPages})}</span>
<Button type="button" variant="outline" size="sm" disabled={page + 1 >= result.totalPages}
onClick={() => setPage(page + 1)}>
{t('ADMIN.NEXT')}<ChevronRight/>
</Button>
</div>
)}
</CardContent>
</Card>
<Dialog open={!!pending} onOpenChange={(open) => { if (!open) closeDialog(); }}>
{pending && (
<DialogContent>
<DialogHeader>
<DialogTitle>
{pending.kind === 'delete'
? t('ADMIN.DELETE_TITLE', {email: pending.user.email})
: pending.user.blocked ? t('ADMIN.UNBLOCK') : t('ADMIN.BLOCK_TITLE', {email: pending.user.email})}
</DialogTitle>
<DialogDescription>
{pending.kind === 'delete' ? t('ADMIN.DELETE_TEXT') : pending.user.blocked ? pending.user.email : t('ADMIN.BLOCK_TEXT')}
</DialogDescription>
</DialogHeader>
{pending.kind === 'delete' && (
<div className="space-y-2">
<Label htmlFor="adminDeleteEmail">{t('ADMIN.TYPE_EMAIL')}</Label>
<Input id="adminDeleteEmail" autoComplete="off" value={typedEmail}
onChange={(event) => setTypedEmail(event.target.value)}/>
</div>
)}
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">{t('ADMIN.CANCEL')}</Button>
</DialogClose>
<Button type="button" variant={pending.kind === 'delete' ? 'destructive' : 'default'}
disabled={confirmDisabled} onClick={confirm}>
{busy && <Loader2 className="animate-spin"/>}
{t(pending.kind === 'delete' ? 'ADMIN.DELETE' : pending.user.blocked ? 'ADMIN.UNBLOCK' : 'ADMIN.BLOCK')}
</Button>
</DialogFooter>
</DialogContent>
)}
</Dialog>
</PageContainer>
);
}
+97
View File
@@ -0,0 +1,97 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter} from 'react-router-dom';
import {toast} from 'sonner';
import AdminUsersPage from './AdminUsersPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('sonner', () => ({toast: {success: vi.fn(), error: vi.fn()}}));
const PLAYER = {
id: 7, email: 'player@example.com', displayName: 'Player', role: 'USER', registrationDate: '2026-09-01T10:00:00',
lastLoginDate: null, steamLinked: true, blocked: false, deletedAt: null,
};
const ADMIN = {...PLAYER, id: 1, email: 'admin@example.com', role: 'PLATFORM_ADMIN', steamLinked: false};
const page = (content, totalPages = 1) => ({content, page: 0, size: 20, totalElements: content.length, totalPages});
const answer = (status, body) => ({ok: status < 300, status, headers: new Headers(), json: async () => body});
const renderPage = () => render(<MemoryRouter><PreferencesProvider><AdminUsersPage/></PreferencesProvider></MemoryRouter>);
const calls = (method) => fetch.mock.calls.filter(([, init]) => (init?.method ?? 'GET') === method);
describe('AdminUsersPage', () => {
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async (url, init) => (init?.method ? answer(204) : answer(200, page([ADMIN, PLAYER]))));
});
afterEach(() => {
cleanup();
localStorage.clear();
vi.clearAllMocks();
});
it('lists the users and offers no action on an admin', async () => {
renderPage();
expect(await screen.findByText('player@example.com')).toBeTruthy();
expect(screen.getByText('admin@example.com')).toBeTruthy();
expect(screen.getAllByRole('button', {name: 'ADMIN.BLOCK'})).toHaveLength(1);
expect(screen.getByText('ADMIN.STEAM')).toBeTruthy();
});
it('searches by the typed text from the first page', async () => {
renderPage();
await screen.findByText('player@example.com');
fireEvent.change(screen.getByPlaceholderText('ADMIN.SEARCH'), {target: {value: ' play '}});
fireEvent.submit(screen.getByPlaceholderText('ADMIN.SEARCH').closest('form'));
await waitFor(() => expect(calls('GET').at(-1)[0]).toContain('query=play&page=0'));
});
it('blocks a user after the confirm and loads the list again', async () => {
renderPage();
fireEvent.click(await screen.findByRole('button', {name: 'ADMIN.BLOCK'}));
fireEvent.click(screen.getAllByRole('button', {name: 'ADMIN.BLOCK'}).at(-1));
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('ADMIN.DONE_BLOCK'));
const [url, init] = calls('PUT')[0];
expect(url).toMatch(/\/api\/admin\/users\/7\/blocked$/);
expect(JSON.parse(init.body)).toEqual({blocked: true});
expect(calls('GET')).toHaveLength(2);
});
it('deletes only after the email is typed', async () => {
renderPage();
fireEvent.click(await screen.findByRole('button', {name: 'ADMIN.DELETE'}));
const confirm = () => screen.getAllByRole('button', {name: 'ADMIN.DELETE'}).at(-1);
expect(confirm().disabled).toBe(true);
fireEvent.change(screen.getByLabelText('ADMIN.TYPE_EMAIL'), {target: {value: 'PLAYER@example.com'}});
fireEvent.click(confirm());
await waitFor(() => expect(calls('DELETE')[0][0]).toMatch(/\/api\/admin\/users\/7$/));
});
it('shows the reason when Auth refuses', async () => {
fetch.mockImplementation(async (url, init) => (init?.method
? answer(409, {code: 'TARGET_IS_ADMIN'}) : answer(200, page([PLAYER]))));
renderPage();
fireEvent.click(await screen.findByRole('button', {name: 'ADMIN.BLOCK'}));
fireEvent.click(screen.getAllByRole('button', {name: 'ADMIN.BLOCK'}).at(-1));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('ADMIN.ERROR_TARGET_IS_ADMIN'));
});
it('says no access to a user without the admin role', async () => {
fetch.mockResolvedValue(answer(403, {}));
renderPage();
expect(await screen.findByText('ADMIN.NO_ACCESS')).toBeTruthy();
});
});
+1
View File
@@ -14,6 +14,7 @@ import {clientFetch} from '../utils/api.js';
const LOGIN_ERROR_KEY = {
INVALID_CREDENTIALS: 'LOGIN.ERROR_INVALID_CREDENTIALS',
TOO_MANY_ATTEMPTS: 'LOGIN.ERROR_TOO_MANY_ATTEMPTS',
ACCOUNT_BLOCKED: 'LOGIN.ERROR_ACCOUNT_BLOCKED',
};
export default function LoginPage() {
+9
View File
@@ -80,4 +80,13 @@ describe('LoginPage', () => {
await waitFor(() => expect(screen.getByText('LOGIN.ERROR_INVALID_CREDENTIALS')).toBeTruthy());
expect(screen.queryByText('LOGIN.SESSION_EXPIRED')).toBeNull();
});
it('says that a blocked account is blocked', async () => {
fetch.mockResolvedValueOnce({ok: false, status: 403, headers: new Headers(), json: async () => ({code: 'ACCOUNT_BLOCKED'})});
renderLogin();
submit();
expect(await screen.findByText('LOGIN.ERROR_ACCOUNT_BLOCKED')).toBeTruthy();
});
});