Public Access
feat(admin): add the admin users page and view as
This commit is contained in:
1 parent
46587dfb5c
commit
afe00ceae9
14 files changed
+649
-8
No files matched your search
@@ -54,6 +54,9 @@ To Be Played is split into three repositories:
|
|||||||
to Core once per page load (`POST /api/library/broken-images`, only with a session). Core repairs it at night;
|
to Core once per page load (`POST /api/library/broken-images`, only with a session). Core repairs it at night;
|
||||||
a repaired cover comes back as `imageUrl`.
|
a repaired cover comes back as `imageUrl`.
|
||||||
- German and English, dark mode, mobile layout, session-expired message instead of a silent logout.
|
- German and English, dark mode, mobile layout, session-expired message instead of a silent logout.
|
||||||
|
- **Admin** (PLATFORM_ADMIN only, `/admin/users`): search the users, block, unblock and delete them (the email is
|
||||||
|
typed to confirm a delete). "View as" in the menu switches the own session to User or Auditor and back; a badge
|
||||||
|
shows the lower role. Auth checks every right on the server.
|
||||||
- **Delete my account** in the settings: a dialog asks for the own email and the password. Auth blocks the
|
- **Delete my account** in the settings: a dialog asks for the own email and the password. Auth blocks the
|
||||||
account at once and removes it after 30 days; the page ends the session and goes to the landing page.
|
account at once and removes it after 30 days; the page ends the session and goes to the landing page.
|
||||||
- **Build version** in the settings: commit and build time of Frontend, Auth and Core, each hash links to its
|
- **Build version** in the settings: commit and build time of Frontend, Auth and Core, each hash links to its
|
||||||
|
|||||||
+46
-2
@@ -15,7 +15,8 @@
|
|||||||
"ERROR_INVALID_CREDENTIALS": "E-Mail oder Passwort ist falsch.",
|
"ERROR_INVALID_CREDENTIALS": "E-Mail oder Passwort ist falsch.",
|
||||||
"ERROR_TOO_MANY_ATTEMPTS": "Zu viele fehlgeschlagene Versuche. Bitte in {{minutes}} Minuten erneut versuchen.",
|
"ERROR_TOO_MANY_ATTEMPTS": "Zu viele fehlgeschlagene Versuche. Bitte in {{minutes}} Minuten erneut versuchen.",
|
||||||
"ERROR_GENERIC": "Anmeldung fehlgeschlagen. Bitte später erneut versuchen.",
|
"ERROR_GENERIC": "Anmeldung fehlgeschlagen. Bitte später erneut versuchen.",
|
||||||
"SESSION_EXPIRED": "Deine Sitzung ist abgelaufen. Bitte melde dich erneut an."
|
"SESSION_EXPIRED": "Deine Sitzung ist abgelaufen. Bitte melde dich erneut an.",
|
||||||
|
"ERROR_ACCOUNT_BLOCKED": "Dieses Konto ist gesperrt. Bitte wende dich an den Admin."
|
||||||
},
|
},
|
||||||
"REGISTRATION": {
|
"REGISTRATION": {
|
||||||
"TITLE": "Registrieren",
|
"TITLE": "Registrieren",
|
||||||
@@ -277,7 +278,13 @@
|
|||||||
"DARK_MODE": "Dunkles Design",
|
"DARK_MODE": "Dunkles Design",
|
||||||
"LIGHT_MODE": "Helles Design",
|
"LIGHT_MODE": "Helles Design",
|
||||||
"PLAY_NEXT": "Nächstes Spiel",
|
"PLAY_NEXT": "Nächstes Spiel",
|
||||||
"STATS": "Statistik"
|
"STATS": "Statistik",
|
||||||
|
"ADMIN": "Admin",
|
||||||
|
"VIEW_AS": {
|
||||||
|
"MENU": "Ansehen als",
|
||||||
|
"BADGE": "Ansicht als {{role}}",
|
||||||
|
"ERROR": "Die Rolle konnte nicht gewechselt werden."
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"BACKLOG": {
|
"BACKLOG": {
|
||||||
"TITLE": "Mein Backlog",
|
"TITLE": "Mein Backlog",
|
||||||
@@ -474,5 +481,42 @@
|
|||||||
"TURN_BASED_STRATEGY_TBS": "Rundenstrategie",
|
"TURN_BASED_STRATEGY_TBS": "Rundenstrategie",
|
||||||
"VISUAL_NOVEL": "Visual Novel"
|
"VISUAL_NOVEL": "Visual Novel"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"ROLES": {
|
||||||
|
"USER": "Nutzer",
|
||||||
|
"AUDITOR": "Prüfer",
|
||||||
|
"PLATFORM_ADMIN": "Admin"
|
||||||
|
},
|
||||||
|
"ADMIN": {
|
||||||
|
"TITLE": "Nutzer",
|
||||||
|
"SEARCH": "E-Mail oder Name suchen",
|
||||||
|
"EMPTY": "Keine Nutzer gefunden.",
|
||||||
|
"NO_ACCESS": "Nur Admins können diese Seite öffnen.",
|
||||||
|
"LOAD_ERROR": "Die Nutzer konnten nicht geladen werden.",
|
||||||
|
"REGISTERED": "Registriert {{date}}",
|
||||||
|
"LAST_LOGIN": "Letzter Login {{date}}",
|
||||||
|
"NEVER": "nie",
|
||||||
|
"STEAM": "Steam",
|
||||||
|
"BLOCKED": "Gesperrt",
|
||||||
|
"DELETED": "Gelöscht",
|
||||||
|
"BLOCK": "Sperren",
|
||||||
|
"UNBLOCK": "Entsperren",
|
||||||
|
"DELETE": "Löschen",
|
||||||
|
"CANCEL": "Abbrechen",
|
||||||
|
"BLOCK_TITLE": "{{email}} sperren?",
|
||||||
|
"BLOCK_TEXT": "Der Nutzer kann sich nicht mehr anmelden; offene Sitzungen enden innerhalb von 15 Minuten. Du kannst später entsperren.",
|
||||||
|
"DELETE_TITLE": "{{email}} löschen?",
|
||||||
|
"DELETE_TEXT": "Das Konto wird sofort gesperrt und nach 30 Tagen mit allen Daten endgültig entfernt.",
|
||||||
|
"TYPE_EMAIL": "Gib zur Bestätigung die E-Mail ein",
|
||||||
|
"DONE_BLOCK": "Nutzer gesperrt.",
|
||||||
|
"DONE_UNBLOCK": "Nutzer entsperrt.",
|
||||||
|
"DONE_DELETE": "Nutzer gelöscht.",
|
||||||
|
"ERROR_SELF_ACTION": "Das geht nicht mit dem eigenen Konto.",
|
||||||
|
"ERROR_TARGET_IS_ADMIN": "Das geht nicht mit einem anderen Admin.",
|
||||||
|
"ERROR_ALREADY_DELETED": "Das Konto ist schon gelöscht.",
|
||||||
|
"ERROR": "Die Aktion ist fehlgeschlagen.",
|
||||||
|
"PAGE_OF": "Seite {{current}} von {{total}}",
|
||||||
|
"PREVIOUS": "Zurück",
|
||||||
|
"NEXT": "Weiter"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+46
-2
@@ -15,7 +15,8 @@
|
|||||||
"ERROR_INVALID_CREDENTIALS": "Email or password is wrong.",
|
"ERROR_INVALID_CREDENTIALS": "Email or password is wrong.",
|
||||||
"ERROR_TOO_MANY_ATTEMPTS": "Too many failed attempts. Please try again in {{minutes}} minutes.",
|
"ERROR_TOO_MANY_ATTEMPTS": "Too many failed attempts. Please try again in {{minutes}} minutes.",
|
||||||
"ERROR_GENERIC": "Login failed. Please try again later.",
|
"ERROR_GENERIC": "Login failed. Please try again later.",
|
||||||
"SESSION_EXPIRED": "Your session has expired. Please log in again."
|
"SESSION_EXPIRED": "Your session has expired. Please log in again.",
|
||||||
|
"ERROR_ACCOUNT_BLOCKED": "This account is blocked. Please contact the admin."
|
||||||
},
|
},
|
||||||
"REGISTRATION": {
|
"REGISTRATION": {
|
||||||
"TITLE": "Register",
|
"TITLE": "Register",
|
||||||
@@ -277,7 +278,13 @@
|
|||||||
"DARK_MODE": "Dark mode",
|
"DARK_MODE": "Dark mode",
|
||||||
"LIGHT_MODE": "Light mode",
|
"LIGHT_MODE": "Light mode",
|
||||||
"PLAY_NEXT": "Play next",
|
"PLAY_NEXT": "Play next",
|
||||||
"STATS": "Stats"
|
"STATS": "Stats",
|
||||||
|
"ADMIN": "Admin",
|
||||||
|
"VIEW_AS": {
|
||||||
|
"MENU": "View as",
|
||||||
|
"BADGE": "Viewing as {{role}}",
|
||||||
|
"ERROR": "The role could not be switched."
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"BACKLOG": {
|
"BACKLOG": {
|
||||||
"TITLE": "My backlog",
|
"TITLE": "My backlog",
|
||||||
@@ -474,5 +481,42 @@
|
|||||||
"TURN_BASED_STRATEGY_TBS": "Turn-based strategy",
|
"TURN_BASED_STRATEGY_TBS": "Turn-based strategy",
|
||||||
"VISUAL_NOVEL": "Visual novel"
|
"VISUAL_NOVEL": "Visual novel"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"ROLES": {
|
||||||
|
"USER": "User",
|
||||||
|
"AUDITOR": "Auditor",
|
||||||
|
"PLATFORM_ADMIN": "Admin"
|
||||||
|
},
|
||||||
|
"ADMIN": {
|
||||||
|
"TITLE": "Users",
|
||||||
|
"SEARCH": "Search email or name",
|
||||||
|
"EMPTY": "No users found.",
|
||||||
|
"NO_ACCESS": "Only admins can open this page.",
|
||||||
|
"LOAD_ERROR": "The users could not be loaded.",
|
||||||
|
"REGISTERED": "Registered {{date}}",
|
||||||
|
"LAST_LOGIN": "Last login {{date}}",
|
||||||
|
"NEVER": "never",
|
||||||
|
"STEAM": "Steam",
|
||||||
|
"BLOCKED": "Blocked",
|
||||||
|
"DELETED": "Deleted",
|
||||||
|
"BLOCK": "Block",
|
||||||
|
"UNBLOCK": "Unblock",
|
||||||
|
"DELETE": "Delete",
|
||||||
|
"CANCEL": "Cancel",
|
||||||
|
"BLOCK_TITLE": "Block {{email}}?",
|
||||||
|
"BLOCK_TEXT": "The user cannot log in any more; open sessions end within 15 minutes. You can unblock later.",
|
||||||
|
"DELETE_TITLE": "Delete {{email}}?",
|
||||||
|
"DELETE_TEXT": "The account is blocked at once and removed for good after 30 days, with all its data.",
|
||||||
|
"TYPE_EMAIL": "Type the email to confirm",
|
||||||
|
"DONE_BLOCK": "User blocked.",
|
||||||
|
"DONE_UNBLOCK": "User unblocked.",
|
||||||
|
"DONE_DELETE": "User deleted.",
|
||||||
|
"ERROR_SELF_ACTION": "You cannot do this to your own account.",
|
||||||
|
"ERROR_TARGET_IS_ADMIN": "You cannot do this to another admin.",
|
||||||
|
"ERROR_ALREADY_DELETED": "The account is already deleted.",
|
||||||
|
"ERROR": "The action failed.",
|
||||||
|
"PAGE_OF": "Page {{current}} of {{total}}",
|
||||||
|
"PREVIOUS": "Previous",
|
||||||
|
"NEXT": "Next"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,7 @@ import ImprintPage from './pages/ImprintPage';
|
|||||||
import Dashboard from "./pages/Dashboard.jsx";
|
import Dashboard from "./pages/Dashboard.jsx";
|
||||||
import RegistrationPage from './pages/RegistrationPage.jsx';
|
import RegistrationPage from './pages/RegistrationPage.jsx';
|
||||||
import SettingsPage from './pages/SettingsPage.jsx';
|
import SettingsPage from './pages/SettingsPage.jsx';
|
||||||
|
import AdminUsersPage from './pages/AdminUsersPage.jsx';
|
||||||
import GameLibrary from './pages/GameLibrary.jsx';
|
import GameLibrary from './pages/GameLibrary.jsx';
|
||||||
import GameDetail from './pages/GameDetail.jsx';
|
import GameDetail from './pages/GameDetail.jsx';
|
||||||
import WishlistPage from './pages/WishlistPage.jsx';
|
import WishlistPage from './pages/WishlistPage.jsx';
|
||||||
@@ -71,6 +72,7 @@ function App() {
|
|||||||
<Route path="/stats" element={<StatsPage/>}/>
|
<Route path="/stats" element={<StatsPage/>}/>
|
||||||
<Route path="/u/:name" element={<PublicProfilePage/>}/>
|
<Route path="/u/:name" element={<PublicProfilePage/>}/>
|
||||||
<Route path="/settings" element={<SettingsPage/>}/>
|
<Route path="/settings" element={<SettingsPage/>}/>
|
||||||
|
<Route path="/admin/users" element={<AdminUsersPage/>}/>
|
||||||
<Route path="/impressum" element={<ImprintPage/>}/>
|
<Route path="/impressum" element={<ImprintPage/>}/>
|
||||||
</Routes>
|
</Routes>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -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 {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 {Button} from '@/components/ui/button';
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import {usePreferences} from '@/context/PreferencesContext.jsx';
|
import {usePreferences} from '@/context/PreferencesContext.jsx';
|
||||||
@@ -15,7 +20,11 @@ import {cn} from '@/lib/utils';
|
|||||||
import Logo from './Logo.jsx';
|
import Logo from './Logo.jsx';
|
||||||
import PageContainer from './PageContainer.jsx';
|
import PageContainer from './PageContainer.jsx';
|
||||||
import SteamAvatar from './SteamAvatar.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 useSteamProfile from '../hooks/useSteamProfile.js';
|
||||||
|
import {ROLES, viewAs} from '../utils/admin.js';
|
||||||
|
import {markSession} from '../utils/auth.js';
|
||||||
|
|
||||||
const NAV_ITEMS = [
|
const NAV_ITEMS = [
|
||||||
{to: '/dashboard', labelKey: 'NAV.DASHBOARD', Icon: LayoutDashboard},
|
{to: '/dashboard', labelKey: 'NAV.DASHBOARD', Icon: LayoutDashboard},
|
||||||
@@ -37,6 +46,30 @@ export default function AppHeader({isAuthenticated, onLogout}) {
|
|||||||
const {isDarkMode, setDarkMode, setLanguage} = usePreferences();
|
const {isDarkMode, setDarkMode, setLanguage} = usePreferences();
|
||||||
const {pathname} = useLocation();
|
const {pathname} = useLocation();
|
||||||
const steamProfile = useSteamProfile(isAuthenticated);
|
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 toggleLanguage = () => setLanguage(i18n.language === 'de' ? 'en' : 'de');
|
||||||
const toggleTheme = () => setDarkMode(!isDarkMode);
|
const toggleTheme = () => setDarkMode(!isDarkMode);
|
||||||
@@ -64,6 +97,9 @@ export default function AppHeader({isAuthenticated, onLogout}) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="ml-auto flex items-center gap-1">
|
<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 ? (
|
{isAuthenticated ? (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
@@ -75,6 +111,24 @@ export default function AppHeader({isAuthenticated, onLogout}) {
|
|||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link to="/settings"><Settings/>{t('NAV.SETTINGS')}</Link>
|
<Link to="/settings"><Settings/>{t('NAV.SETTINGS')}</Link>
|
||||||
</DropdownMenuItem>
|
</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}>
|
<DropdownMenuItem onSelect={toggleLanguage}>
|
||||||
<Languages/>{t('NAV.LANGUAGE')}: {i18n.language.toUpperCase()}
|
<Languages/>{t('NAV.LANGUAGE')}: {i18n.language.toUpperCase()}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|||||||
@@ -1,13 +1,30 @@
|
|||||||
// @vitest-environment jsdom
|
// @vitest-environment jsdom
|
||||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
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 {MemoryRouter} from 'react-router-dom';
|
||||||
import AppHeader from './AppHeader.jsx';
|
import AppHeader from './AppHeader.jsx';
|
||||||
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
|
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
|
||||||
|
|
||||||
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
|
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', () => {
|
describe('AppHeader', () => {
|
||||||
// jsdom applies no media queries, so the test hides the name the way the 380px breakpoint does.
|
// 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();
|
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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -14,6 +14,7 @@ import {clientFetch} from '../utils/api.js';
|
|||||||
const LOGIN_ERROR_KEY = {
|
const LOGIN_ERROR_KEY = {
|
||||||
INVALID_CREDENTIALS: 'LOGIN.ERROR_INVALID_CREDENTIALS',
|
INVALID_CREDENTIALS: 'LOGIN.ERROR_INVALID_CREDENTIALS',
|
||||||
TOO_MANY_ATTEMPTS: 'LOGIN.ERROR_TOO_MANY_ATTEMPTS',
|
TOO_MANY_ATTEMPTS: 'LOGIN.ERROR_TOO_MANY_ATTEMPTS',
|
||||||
|
ACCOUNT_BLOCKED: 'LOGIN.ERROR_ACCOUNT_BLOCKED',
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
|
|||||||
@@ -80,4 +80,13 @@ describe('LoginPage', () => {
|
|||||||
await waitFor(() => expect(screen.getByText('LOGIN.ERROR_INVALID_CREDENTIALS')).toBeTruthy());
|
await waitFor(() => expect(screen.getByText('LOGIN.ERROR_INVALID_CREDENTIALS')).toBeTruthy());
|
||||||
expect(screen.queryByText('LOGIN.SESSION_EXPIRED')).toBeNull();
|
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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -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}),
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -44,6 +44,16 @@ export function refreshSession() {
|
|||||||
return runningRefresh;
|
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,
|
* 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
|
* the 401 goes back to the caller. Ending the session is the caller's job (useSessionExpired), so the user sees
|
||||||
|
|||||||
Reference in new issue
Block a user