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

+2
View File
@@ -8,6 +8,7 @@ import ImprintPage from './pages/ImprintPage';
import Dashboard from "./pages/Dashboard.jsx";
import RegistrationPage from './pages/RegistrationPage.jsx';
import SettingsPage from './pages/SettingsPage.jsx';
import AdminUsersPage from './pages/AdminUsersPage.jsx';
import GameLibrary from './pages/GameLibrary.jsx';
import GameDetail from './pages/GameDetail.jsx';
import WishlistPage from './pages/WishlistPage.jsx';
@@ -71,6 +72,7 @@ function App() {
<Route path="/stats" element={<StatsPage/>}/>
<Route path="/u/:name" element={<PublicProfilePage/>}/>
<Route path="/settings" element={<SettingsPage/>}/>
<Route path="/admin/users" element={<AdminUsersPage/>}/>
<Route path="/impressum" element={<ImprintPage/>}/>
</Routes>
</main>
+56 -2
View File
@@ -1,13 +1,18 @@
import {Link, NavLink, useLocation} from 'react-router-dom';
import {Link, NavLink, useLocation, useNavigate} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {ChartColumn, Dices, Languages, LayoutDashboard, Library, LogOut, Moon, Settings, Sun} from 'lucide-react';
import {ChartColumn, Dices, Eye, Languages, LayoutDashboard, Library, LogOut, Moon, Settings, Shield, Sun} from 'lucide-react';
import {toast} from 'sonner';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {usePreferences} from '@/context/PreferencesContext.jsx';
@@ -15,7 +20,11 @@ import {cn} from '@/lib/utils';
import Logo from './Logo.jsx';
import PageContainer from './PageContainer.jsx';
import SteamAvatar from './SteamAvatar.jsx';
import useCurrentUser from '../hooks/useCurrentUser.js';
import useSessionExpired from '../hooks/useSessionExpired.js';
import useSteamProfile from '../hooks/useSteamProfile.js';
import {ROLES, viewAs} from '../utils/admin.js';
import {markSession} from '../utils/auth.js';
const NAV_ITEMS = [
{to: '/dashboard', labelKey: 'NAV.DASHBOARD', Icon: LayoutDashboard},
@@ -37,6 +46,30 @@ export default function AppHeader({isAuthenticated, onLogout}) {
const {isDarkMode, setDarkMode, setLanguage} = usePreferences();
const {pathname} = useLocation();
const steamProfile = useSteamProfile(isAuthenticated);
const currentUser = useCurrentUser(isAuthenticated);
const navigate = useNavigate();
const expireSession = useSessionExpired();
const isAdmin = currentUser?.role === 'PLATFORM_ADMIN';
const viewingAs = currentUser && currentUser.activeRole !== currentUser.role ? currentUser.activeRole : null;
const switchRole = async (role) => {
try {
const response = await viewAs(role === currentUser.role ? null : role);
if (response.ok) {
// New cookies with the other role; the new stamp makes the header and pages load again.
markSession();
navigate('/dashboard');
return;
}
if (response.status === 401) {
expireSession();
return;
}
} catch (err) {
console.error('View as error:', err);
}
toast.error(t('NAV.VIEW_AS.ERROR'));
};
const toggleLanguage = () => setLanguage(i18n.language === 'de' ? 'en' : 'de');
const toggleTheme = () => setDarkMode(!isDarkMode);
@@ -64,6 +97,9 @@ export default function AppHeader({isAuthenticated, onLogout}) {
)}
<div className="ml-auto flex items-center gap-1">
{isAuthenticated && viewingAs && (
<Badge variant="secondary" className="mr-1">{t('NAV.VIEW_AS.BADGE', {role: t(`ROLES.${viewingAs}`)})}</Badge>
)}
{isAuthenticated ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -75,6 +111,24 @@ export default function AppHeader({isAuthenticated, onLogout}) {
<DropdownMenuItem asChild>
<Link to="/settings"><Settings/>{t('NAV.SETTINGS')}</Link>
</DropdownMenuItem>
{isAdmin && !viewingAs && (
<DropdownMenuItem asChild>
<Link to="/admin/users"><Shield/>{t('NAV.ADMIN')}</Link>
</DropdownMenuItem>
)}
{isAdmin && (
<DropdownMenuSub>
<DropdownMenuSubTrigger><Eye/>{t('NAV.VIEW_AS.MENU')}</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
{ROLES.map((role) => (
<DropdownMenuItem key={role} disabled={role === currentUser.activeRole}
onSelect={() => switchRole(role)}>
{t(`ROLES.${role}`)}
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
</DropdownMenuSub>
)}
<DropdownMenuItem onSelect={toggleLanguage}>
<Languages/>{t('NAV.LANGUAGE')}: {i18n.language.toUpperCase()}
</DropdownMenuItem>
+51 -2
View File
@@ -1,13 +1,30 @@
// @vitest-environment jsdom
import {afterEach, describe, expect, it, vi} from 'vitest';
import {cleanup, render, screen} from '@testing-library/react';
import {cleanup, fireEvent, render, screen} from '@testing-library/react';
import {MemoryRouter} from 'react-router-dom';
import AppHeader from './AppHeader.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
afterEach(cleanup);
afterEach(() => {
cleanup();
localStorage.clear();
});
const loggedInAs = (me) => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async (url) => ({
ok: true, status: 200, json: async () => (url.includes('/api/users/me') ? me : {}),
}));
render(
<MemoryRouter>
<PreferencesProvider><AppHeader isAuthenticated onLogout={() => {}}/></PreferencesProvider>
</MemoryRouter>,
);
};
const openMenu = () => fireEvent.keyDown(screen.getByRole('button', {name: 'NAV.MENU'}), {key: 'Enter'});
describe('AppHeader', () => {
// jsdom applies no media queries, so the test hides the name the way the 380px breakpoint does.
@@ -21,4 +38,36 @@ describe('AppHeader', () => {
expect(screen.getByRole('link', {name: 'ToBePlayed'})).toBeTruthy();
});
it('offers the admin page and "view as" to an admin', async () => {
loggedInAs({role: 'PLATFORM_ADMIN', activeRole: 'PLATFORM_ADMIN'});
await screen.findByRole('button', {name: 'NAV.MENU'});
await vi.waitFor(() => expect(fetch).toHaveBeenCalledWith(expect.stringContaining('/api/users/me'), expect.anything()));
openMenu();
expect(await screen.findByText('NAV.ADMIN')).toBeTruthy();
expect(screen.getByText('NAV.VIEW_AS.MENU')).toBeTruthy();
expect(screen.queryByText('NAV.VIEW_AS.BADGE')).toBeNull();
});
it('shows the badge and hides the admin page while an admin views as a user', async () => {
loggedInAs({role: 'PLATFORM_ADMIN', activeRole: 'USER'});
expect(await screen.findByText('NAV.VIEW_AS.BADGE')).toBeTruthy();
openMenu();
expect(await screen.findByText('NAV.VIEW_AS.MENU')).toBeTruthy();
expect(screen.queryByText('NAV.ADMIN')).toBeNull();
});
it('offers nothing of that to a user', async () => {
loggedInAs({role: 'USER', activeRole: 'USER'});
await vi.waitFor(() => expect(fetch).toHaveBeenCalledWith(expect.stringContaining('/api/users/me'), expect.anything()));
openMenu();
expect(await screen.findByText('NAV.SETTINGS')).toBeTruthy();
expect(screen.queryByText('NAV.ADMIN')).toBeNull();
expect(screen.queryByText('NAV.VIEW_AS.MENU')).toBeNull();
});
});
+34
View File
@@ -0,0 +1,34 @@
import {useEffect, useState} from 'react';
import {apiFetch} from '../utils/api.js';
import {sessionStamp} from '../utils/auth.js';
/**
* The stored role and the active role ("view as") of the logged-in user, or null while loading and on any error.
* Loads again after a new login or a role switch (see sessionStamp) on the next render.
*/
export default function useCurrentUser(enabled) {
const [user, setUser] = useState(null);
const stamp = sessionStamp();
useEffect(() => {
if (!enabled || !stamp) {
setUser(null);
return undefined;
}
let cancelled = false;
(async () => {
try {
const response = await apiFetch(`${import.meta.env.VITE_API_URL}/api/users/me?v=1`);
const data = response.ok ? await response.json() : null;
if (!cancelled) setUser(data && {role: data.role, activeRole: data.activeRole ?? data.role});
} catch {
if (!cancelled) setUser(null);
}
})();
return () => {
cancelled = true;
};
}, [enabled, stamp]);
return user;
}
+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();
});
});
+34
View File
@@ -0,0 +1,34 @@
import {apiFetch, rotatingFetch} from './api.js';
const AUTH = () => import.meta.env.VITE_API_URL;
export const ROLES = ['USER', 'AUDITOR', 'PLATFORM_ADMIN'];
/**
* GET /api/admin/users: {content, page, size, totalElements, totalPages}. PLATFORM_ADMIN only (403 otherwise).
*/
export const fetchUsers = (query, page, size) =>
apiFetch(`${AUTH()}/api/admin/users?${new URLSearchParams({query, page, size})}`);
/**
* 204, or 409 with code SELF_ACTION, TARGET_IS_ADMIN or ALREADY_DELETED.
*/
export const setUserBlocked = (userId, blocked) =>
apiFetch(`${AUTH()}/api/admin/users/${userId}/blocked`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({blocked}),
});
export const deleteUser = (userId) => apiFetch(`${AUTH()}/api/admin/users/${userId}`, {method: 'DELETE'});
/**
* "View as": new cookies that act with the role; null goes back to the own role. Under /api/auth, so it needs the
* refresh cookie and no access token; 403 ROLE_NOT_ALLOWED above the own role.
*/
export const viewAs = (role) =>
rotatingFetch(`${AUTH()}/api/auth/view-as`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({role}),
});
+25
View File
@@ -0,0 +1,25 @@
// @vitest-environment jsdom
import {describe, expect, it, vi} from 'vitest';
import {refreshSession} from './api.js';
import {viewAs} from './admin.js';
describe('viewAs', () => {
it('waits for a running refresh before it sends the refresh cookie', async () => {
let finishRefresh;
globalThis.fetch = vi.fn((url) => (url.endsWith('/api/auth/refresh')
? new Promise((resolve) => {
finishRefresh = () => resolve({ok: true, status: 204});
})
: Promise.resolve({ok: true, status: 204})));
const refreshing = refreshSession();
const switching = viewAs('USER');
await Promise.resolve();
expect(fetch.mock.calls.map(([url]) => url).filter((url) => url.endsWith('/api/auth/view-as'))).toHaveLength(0);
finishRefresh();
await refreshing;
await switching;
});
});
+10
View File
@@ -44,6 +44,16 @@ export function refreshSession() {
return runningRefresh;
}
/**
* A request that rotates the refresh token like a refresh (e.g. "view as"). It waits for a running refresh and
* takes the same lock, so no two requests send one refresh token.
*/
export async function rotatingFetch(url, init = {}) {
await runningRefresh?.catch(() => undefined);
const send = () => clientFetch(url, init);
return globalThis.navigator?.locks ? navigator.locks.request('tbp-refresh', send) : send();
}
/**
* fetch for the logged-in user. A 401 renews the access cookie once and sends the request again. When that fails,
* the 401 goes back to the caller. Ending the session is the caller's job (useSessionExpired), so the user sees