fix(admin): guard GET /api/users/{id} with @RequirePermission(ADMIN_USER)

Fixes IDOR: the endpoint was publicly accessible to any authenticated user.
Now requires ADMIN_USER permission, matching all other user management endpoints.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-03-30 01:09:40 +02:00
committed by marcel
parent c61b08d6de
commit 9cacc6079e
22 changed files with 844 additions and 346 deletions

View File

@@ -61,6 +61,7 @@ public class UserController {
}
@GetMapping("users/{id}")
@RequirePermission(Permission.ADMIN_USER)
public ResponseEntity<AppUser> getUser(@PathVariable UUID id) {
AppUser user = userService.getById(id);
user.setPassword(null);

View File

@@ -50,4 +50,29 @@ class UserControllerTest {
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("anna"));
}
// ─── GET /api/users/{id} ──────────────────────────────────────────────────
@Test
@WithMockUser(username = "reader")
void getUser_returns403_whenCallerLacksAdminUserPermission() throws Exception {
UUID id = UUID.randomUUID();
AppUser target = AppUser.builder().id(id).username("target").build();
when(userService.getById(id)).thenReturn(target);
mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(username = "admin", authorities = {"ADMIN_USER"})
void getUser_returns200_whenCallerHasAdminUserPermission() throws Exception {
UUID id = UUID.randomUUID();
AppUser user = AppUser.builder().id(id).username("target").build();
when(userService.getById(id)).thenReturn(user);
mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("target"));
}
}

View File

@@ -167,6 +167,10 @@
"admin_group_name_placeholder": "Gruppenname (z.B. Editoren)",
"admin_user_delete_confirm": "Benutzer {username} wirklich löschen?",
"admin_btn_new_user": "Neuer Benutzer",
"admin_users_list_title": "Alle Benutzer",
"admin_users_search_placeholder": "Benutzer suchen\u2026",
"admin_users_empty": "Keine Benutzer vorhanden.",
"admin_users_select_prompt": "W\u00e4hle einen Benutzer aus der Liste.",
"admin_user_new_heading": "Neuen Benutzer anlegen",
"admin_user_edit_heading": "Benutzer bearbeiten: {username}",
"admin_user_created": "Benutzer wurde erstellt.",

View File

@@ -167,6 +167,10 @@
"admin_group_name_placeholder": "Group name (e.g. Editors)",
"admin_user_delete_confirm": "Really delete user {username}?",
"admin_btn_new_user": "New User",
"admin_users_list_title": "All Users",
"admin_users_search_placeholder": "Search users\u2026",
"admin_users_empty": "No users found.",
"admin_users_select_prompt": "Select a user from the list.",
"admin_user_new_heading": "Create new user",
"admin_user_edit_heading": "Edit user: {username}",
"admin_user_created": "User has been created.",

View File

@@ -167,6 +167,10 @@
"admin_group_name_placeholder": "Nombre del grupo (p.ej. Editores)",
"admin_user_delete_confirm": "¿Realmente eliminar al usuario {username}?",
"admin_btn_new_user": "Nuevo usuario",
"admin_users_list_title": "Todos los usuarios",
"admin_users_search_placeholder": "Buscar usuarios\u2026",
"admin_users_empty": "No hay usuarios.",
"admin_users_select_prompt": "Selecciona un usuario de la lista.",
"admin_user_new_heading": "Crear nuevo usuario",
"admin_user_edit_heading": "Editar usuario: {username}",
"admin_user_created": "Usuario creado.",

View File

@@ -0,0 +1,34 @@
<script lang="ts">
import { page } from '$app/state';
import EntityNav from './EntityNav.svelte';
let { data, children } = $props();
const isSystem = $derived(page.url.pathname.startsWith('/admin/system'));
</script>
<svelte:head>
<title>Admin · Familienarchiv</title>
</svelte:head>
<!--
-mt-6: cancel the global layout's pt-6 on <main>
Height fills from below the global header (64px) to bottom of viewport.
-->
<div class="-mt-6 flex overflow-hidden" style="height: calc(100vh - 65px)">
<!-- Entity Nav: always visible on desktop, icon strip on tablet (Phase 9) -->
<EntityNav
userCount={data.userCount}
groupCount={data.groupCount}
tagCount={data.tagCount}
canManageUsers={data.canManageUsers}
canManageTags={data.canManageTags}
canManageGroups={data.canManageGroups}
canRunMaintenance={data.canRunMaintenance}
/>
<!-- Right side: list panel + detail panel (or full-width for system) -->
<div class="flex min-w-0 flex-1 overflow-hidden">
{@render children()}
</div>
</div>

View File

@@ -1,78 +1,68 @@
<script lang="ts">
import { slide } from 'svelte/transition';
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import UsersTab from './UsersTab.svelte';
import TagsTab from './TagsTab.svelte';
import GroupsTab from './GroupsTab.svelte';
import SystemTab from './SystemTab.svelte';
let { data, form } = $props();
let { data } = $props();
let activeTab = $state('users');
// On desktop/tablet the layout shell with EntityNav is visible.
// On mobile this page IS the entity picker — tapping an entity pushes
// the user to that route so the browser back button returns here.
onMount(() => {
if (window.matchMedia('(min-width: 768px)').matches) {
goto('/admin/users', { replaceState: true });
}
});
</script>
<svelte:head>
<title>{m.page_title_admin()}</title>
</svelte:head>
<div class="mx-auto max-w-7xl px-4 py-8 font-sans sm:px-6 lg:px-8">
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<h1 class="font-serif text-3xl text-ink">{m.admin_heading()}</h1>
<!-- Tabs -->
<div class="grid grid-cols-2 rounded-lg border border-line bg-surface p-1 shadow-sm sm:flex">
<button
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
'users'
? 'bg-primary text-primary-fg'
: 'text-ink-2 hover:text-ink'}"
onclick={() => (activeTab = 'users')}>{m.admin_tab_users()}</button
>
<button
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
'groups'
? 'bg-primary text-primary-fg'
: 'text-ink-2 hover:text-ink'}"
onclick={() => (activeTab = 'groups')}>{m.admin_tab_groups()}</button
>
<button
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
'tags'
? 'bg-primary text-primary-fg'
: 'text-ink-2 hover:text-ink'}"
onclick={() => (activeTab = 'tags')}>{m.admin_tab_tags()}</button
>
<button
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
'system'
? 'bg-primary text-primary-fg'
: 'text-ink-2 hover:text-ink'}"
onclick={() => (activeTab = 'system')}>{m.admin_tab_system()}</button
>
</div>
<!-- Mobile entity picker (md+ viewports redirect to /admin/users on mount) -->
<div class="flex flex-1 flex-col bg-surface">
<div class="border-b border-line px-4 py-4">
<h1 class="font-sans text-lg font-bold text-ink">{m.admin_heading()}</h1>
</div>
{#if form?.message}
<div class="mb-6 rounded border border-accent/50 bg-accent/20 p-4 text-ink">
{form.message}
</div>
{/if}
<nav class="divide-y divide-line" aria-label={m.admin_heading()}>
{#if data.canManageUsers}
<a href="/admin/users" class="flex items-center justify-between px-4 py-4 hover:bg-muted">
<div>
<div class="font-sans text-sm font-bold text-ink">{m.admin_tab_users()}</div>
<div class="mt-0.5 font-sans text-xs text-ink-3">{data.userCount}</div>
</div>
<span class="text-ink-3"></span>
</a>
{/if}
{#if activeTab === 'users'}
<div in:slide>
<UsersTab users={data.users} />
</div>
{:else if activeTab === 'tags'}
<div in:slide>
<TagsTab tags={data.tags} />
</div>
{:else if activeTab === 'groups'}
<div in:slide>
<GroupsTab groups={data.groups} />
</div>
{:else if activeTab === 'system'}
<div in:slide>
<SystemTab />
</div>
{/if}
{#if data.canManageGroups}
<a href="/admin/groups" class="flex items-center justify-between px-4 py-4 hover:bg-muted">
<div>
<div class="font-sans text-sm font-bold text-ink">{m.admin_tab_groups()}</div>
<div class="mt-0.5 font-sans text-xs text-ink-3">{data.groupCount}</div>
</div>
<span class="text-ink-3"></span>
</a>
{/if}
{#if data.canManageTags}
<a href="/admin/tags" class="flex items-center justify-between px-4 py-4 hover:bg-muted">
<div>
<div class="font-sans text-sm font-bold text-ink">{m.admin_tab_tags()}</div>
<div class="mt-0.5 font-sans text-xs text-ink-3">{data.tagCount}</div>
</div>
<span class="text-ink-3"></span>
</a>
{/if}
{#if data.canRunMaintenance}
<a href="/admin/system" class="flex items-center justify-between px-4 py-4 hover:bg-muted">
<div>
<div class="font-sans text-sm font-bold text-ink">{m.admin_tab_system()}</div>
</div>
<span class="text-ink-3"></span>
</a>
{/if}
</nav>
</div>

View File

@@ -0,0 +1,114 @@
<script lang="ts">
import { page } from '$app/state';
import { m } from '$lib/paraglide/messages.js';
let {
userCount,
groupCount,
tagCount,
canManageUsers,
canManageTags,
canManageGroups,
canRunMaintenance
}: {
userCount: number;
groupCount: number;
tagCount: number;
canManageUsers: boolean;
canManageTags: boolean;
canManageGroups: boolean;
canRunMaintenance: boolean;
} = $props();
const currentPath = $derived(page.url.pathname);
const isActive = (section: string) => currentPath.startsWith(`/admin/${section}`);
</script>
<nav class="flex w-30 flex-shrink-0 flex-col bg-brand-navy" aria-label={m.admin_heading()}>
<div class="px-3 pt-3 pb-1 text-[9px] font-extrabold tracking-widest text-white/30 uppercase">
{m.admin_heading()}
</div>
{#if canManageUsers}
<a
href="/admin/users"
class="flex flex-col gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors
{isActive('users')
? 'border-brand-mint bg-white/10'
: 'border-transparent hover:bg-white/5'}"
aria-current={isActive('users') ? 'page' : undefined}
>
<span class="text-[13px] font-black {isActive('users') ? 'text-white/65' : 'text-white/20'}">
{userCount}
</span>
<span
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
{isActive('users') ? 'text-white' : 'text-white/55'}"
>
{m.admin_tab_users()}
</span>
</a>
{/if}
{#if canManageGroups}
<a
href="/admin/groups"
class="flex flex-col gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors
{isActive('groups')
? 'border-brand-mint bg-white/10'
: 'border-transparent hover:bg-white/5'}"
aria-current={isActive('groups') ? 'page' : undefined}
>
<span class="text-[13px] font-black {isActive('groups') ? 'text-white/65' : 'text-white/20'}">
{groupCount}
</span>
<span
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
{isActive('groups') ? 'text-white' : 'text-white/55'}"
>
{m.admin_tab_groups()}
</span>
</a>
{/if}
{#if canManageTags}
<a
href="/admin/tags"
class="flex flex-col gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors
{isActive('tags')
? 'border-brand-mint bg-white/10'
: 'border-transparent hover:bg-white/5'}"
aria-current={isActive('tags') ? 'page' : undefined}
>
<span class="text-[13px] font-black {isActive('tags') ? 'text-white/65' : 'text-white/20'}">
{tagCount}
</span>
<span
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
{isActive('tags') ? 'text-white' : 'text-white/55'}"
>
{m.admin_tab_tags()}
</span>
</a>
{/if}
<div class="flex-1"></div>
{#if canRunMaintenance}
<a
href="/admin/system"
class="flex flex-col gap-0.5 border-t border-l-[3px] border-white/10 px-3.5 py-2.5 transition-colors
{isActive('system')
? 'border-brand-mint bg-white/10'
: 'border-l-transparent hover:bg-white/5'}"
aria-current={isActive('system') ? 'page' : undefined}
>
<span
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
{isActive('system') ? 'text-white' : 'text-white/55'}"
>
{m.admin_tab_system()}
</span>
</a>
{/if}
</nav>

View File

@@ -29,64 +29,65 @@ let {
</a>
</div>
<table class="min-w-full divide-y divide-line">
<thead class="bg-muted">
<tr>
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_login()}</th
>
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_full_name()}</th
>
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_groups()}</th
>
<th class="px-6 py-3 text-right text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_actions()}</th
>
</tr>
</thead>
<tbody class="divide-y divide-line bg-surface">
{#each users as user (user.id)}
<tr class="group/row hover:bg-muted">
<td class="px-6 py-4 text-sm font-medium whitespace-nowrap text-ink">
{user.username}
</td>
<td class="px-6 py-4 text-sm whitespace-nowrap text-ink-2">
{#if user.firstName || user.lastName}
{user.firstName ?? ''} {user.lastName ?? ''}
{:else}
<span class="text-ink-3 italic"></span>
{/if}
</td>
<td class="px-6 py-4 text-sm text-ink-2">
<div class="flex flex-wrap gap-1">
{#if user.groups && user.groups.length > 0}
{#each user.groups as group (group.id)}
<span
class="rounded-full border border-blue-100 bg-blue-50 px-2 py-0.5 text-[10px] font-bold text-blue-700 uppercase"
>
{group.name}
</span>
{/each}
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-line">
<thead class="bg-muted">
<tr>
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_login()}</th
>
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_full_name()}</th
>
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_groups()}</th
>
<th class="px-6 py-3 text-right text-xs font-bold tracking-wider text-ink-2 uppercase"
>{m.admin_col_actions()}</th
>
</tr>
</thead>
<tbody class="divide-y divide-line bg-surface">
{#each users as user (user.id)}
<tr class="group/row hover:bg-muted">
<td class="px-6 py-4 text-sm font-medium whitespace-nowrap text-ink">
{user.username}
</td>
<td class="px-6 py-4 text-sm whitespace-nowrap text-ink-2">
{#if user.firstName || user.lastName}
{user.firstName ?? ''} {user.lastName ?? ''}
{:else}
<span class="text-xs text-ink-3 italic">{m.admin_no_groups()}</span>
<span class="text-ink-3 italic"></span>
{/if}
</div>
</td>
<td class="px-6 py-4 text-right whitespace-nowrap">
<div class="flex items-center justify-end gap-4">
<a
href="/admin/users/{user.id}"
class="text-sm font-bold tracking-wide text-primary uppercase hover:text-ink-2"
>
{m.btn_edit()}
</a>
</td>
<td class="px-6 py-4 text-sm text-ink-2">
<div class="flex flex-wrap gap-1">
{#if user.groups && user.groups.length > 0}
{#each user.groups as group (group.id)}
<span
class="rounded-full border border-blue-100 bg-blue-50 px-2 py-0.5 text-[10px] font-bold text-blue-700 uppercase"
>
{group.name}
</span>
{/each}
{:else}
<span class="text-xs text-ink-3 italic">{m.admin_no_groups()}</span>
{/if}
</div>
</td>
<td class="px-6 py-4 text-right whitespace-nowrap">
<div class="flex items-center justify-end gap-4">
<a
href="/admin/users/{user.id}"
class="text-sm font-bold tracking-wide text-primary uppercase hover:text-ink-2"
>
{m.btn_edit()}
</a>
<form
method="POST"
action="?/deleteUser"
use:enhance={({ cancel }) => {
<form
method="POST"
action="?/deleteUser"
use:enhance={({ cancel }) => {
if (!confirm(m.admin_user_delete_confirm({ username: user.username }))) {
cancel();
}
@@ -94,27 +95,28 @@ let {
await update();
};
}}
class="flex items-center"
>
<input type="hidden" name="id" value={user.id} />
<button
class="p-1 text-ink-3 transition-colors hover:text-red-600"
title={m.admin_btn_delete_user_title()}
class="flex items-center"
>
<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
</button>
</form>
</div>
</td>
</tr>
{/each}
</tbody>
</table>
<input type="hidden" name="id" value={user.id} />
<button
class="p-1 text-ink-3 transition-colors hover:text-red-600"
title={m.admin_btn_delete_user_title()}
>
<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
</button>
</form>
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>

View File

@@ -0,0 +1,87 @@
/**
* Layout shell tests — we test EntityNav.svelte directly since the layout
* itself is a thin shell that just composes EntityNav and renders children.
*/
import { afterEach, describe, it, expect, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import EntityNav from './EntityNav.svelte';
vi.mock('$app/state', () => ({
page: { url: { pathname: '/admin/users' } }
}));
afterEach(cleanup);
const fullPerms = {
userCount: 4,
groupCount: 3,
tagCount: 7,
canManageUsers: true,
canManageTags: true,
canManageGroups: true,
canRunMaintenance: true
};
describe('admin EntityNav — links', () => {
it('renders users nav link pointing to /admin/users', async () => {
render(EntityNav, fullPerms);
await expect
.element(page.getByRole('link', { name: /benutzer/i }))
.toHaveAttribute('href', '/admin/users');
});
it('renders groups nav link pointing to /admin/groups', async () => {
render(EntityNav, fullPerms);
await expect
.element(page.getByRole('link', { name: /gruppen/i }))
.toHaveAttribute('href', '/admin/groups');
});
it('renders tags nav link pointing to /admin/tags', async () => {
render(EntityNav, fullPerms);
await expect
.element(page.getByRole('link', { name: /schlagworte/i }))
.toHaveAttribute('href', '/admin/tags');
});
it('renders system nav link pointing to /admin/system', async () => {
render(EntityNav, fullPerms);
await expect
.element(page.getByRole('link', { name: /system/i }))
.toHaveAttribute('href', '/admin/system');
});
});
describe('admin EntityNav — permission-based rendering', () => {
it('hides users link when canManageUsers is false', async () => {
render(EntityNav, { ...fullPerms, canManageUsers: false });
await expect.element(page.getByRole('link', { name: /benutzer/i })).not.toBeInTheDocument();
});
it('hides tags link when canManageTags is false', async () => {
render(EntityNav, { ...fullPerms, canManageTags: false });
await expect.element(page.getByRole('link', { name: /schlagworte/i })).not.toBeInTheDocument();
});
it('hides system link when canRunMaintenance is false', async () => {
render(EntityNav, { ...fullPerms, canRunMaintenance: false });
await expect.element(page.getByRole('link', { name: /system/i })).not.toBeInTheDocument();
});
});
describe('admin EntityNav — active state', () => {
it('marks users link as aria-current=page when on /admin/users', async () => {
render(EntityNav, fullPerms);
await expect
.element(page.getByRole('link', { name: /benutzer/i }))
.toHaveAttribute('aria-current', 'page');
});
it('does not mark groups link as current when on /admin/users', async () => {
render(EntityNav, fullPerms);
await expect
.element(page.getByRole('link', { name: /gruppen/i }))
.not.toHaveAttribute('aria-current');
});
});

View File

@@ -1,83 +1,73 @@
/**
* Tests for the admin root page — the mobile entity picker.
* On md+ viewports the page immediately redirects to /admin/users (tested
* in e2e). Here we verify the mobile-only list of entity links.
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import Page from './+page.svelte';
vi.mock('$app/forms', () => ({ enhance: () => () => {} }));
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
const makeGroup = (overrides = {}) => ({
id: 'g1',
name: 'Editoren',
permissions: ['WRITE_ALL'],
...overrides
});
const makeUser = (overrides = {}) => ({
id: 'u1',
username: 'max',
firstName: 'Max',
lastName: 'Mustermann',
email: 'max@example.com',
birthDate: undefined,
contact: undefined,
enabled: true,
groups: [makeGroup()],
createdAt: '2024-01-01T00:00:00Z',
...overrides
});
const baseData = {
user: undefined,
canWrite: true,
canAnnotate: false,
users: [makeUser()],
groups: [makeGroup()],
tags: []
const fullData = {
userCount: 4,
groupCount: 3,
tagCount: 7,
canManageUsers: true,
canManageTags: true,
canManageGroups: true,
canRunMaintenance: true
};
afterEach(cleanup);
// ─── Users tab ────────────────────────────────────────────────────────────────
describe('Admin page users tab', () => {
it('shows the username in the table', async () => {
render(Page, { data: baseData, form: null });
await expect.element(page.getByRole('cell', { name: 'max', exact: true })).toBeInTheDocument();
describe('Admin root page entity picker', () => {
it('renders the admin heading', async () => {
render(Page, { data: fullData });
await expect.element(page.getByRole('heading')).toBeInTheDocument();
});
it('shows the full name in the table', async () => {
render(Page, { data: baseData, form: null });
await expect.element(page.getByText(/Max Mustermann/)).toBeInTheDocument();
});
it('shows a dash when user has no name set', async () => {
const data = { ...baseData, users: [makeUser({ firstName: undefined, lastName: undefined })] };
render(Page, { data, form: null });
await expect.element(page.getByText('')).toBeInTheDocument();
});
it('shows group badges for the user', async () => {
render(Page, { data: baseData, form: null });
await expect.element(page.getByText('Editoren')).toBeInTheDocument();
});
it('edit link points to /admin/users/[id]', async () => {
render(Page, { data: baseData, form: null });
it('renders users link pointing to /admin/users', async () => {
render(Page, { data: fullData });
await expect
.element(page.getByRole('link', { name: /Bearbeiten/i }))
.toHaveAttribute('href', '/admin/users/u1');
.element(page.getByRole('link', { name: /benutzer/i }))
.toHaveAttribute('href', '/admin/users');
});
it('new user button links to /admin/users/new', async () => {
render(Page, { data: baseData, form: null });
it('renders groups link pointing to /admin/groups', async () => {
render(Page, { data: fullData });
await expect
.element(page.getByRole('link', { name: /Neuer Benutzer/i }))
.toHaveAttribute('href', '/admin/users/new');
.element(page.getByRole('link', { name: /gruppen/i }))
.toHaveAttribute('href', '/admin/groups');
});
it('shows "no groups" label when user has no groups', async () => {
const data = { ...baseData, users: [makeUser({ groups: [] })] };
render(Page, { data, form: null });
await expect.element(page.getByText(/Keine Gruppen/i)).toBeInTheDocument();
it('renders tags link pointing to /admin/tags', async () => {
render(Page, { data: fullData });
await expect
.element(page.getByRole('link', { name: /schlagworte/i }))
.toHaveAttribute('href', '/admin/tags');
});
it('renders system link pointing to /admin/system', async () => {
render(Page, { data: fullData });
await expect
.element(page.getByRole('link', { name: /system/i }))
.toHaveAttribute('href', '/admin/system');
});
it('hides users link when canManageUsers is false', async () => {
render(Page, { data: { ...fullData, canManageUsers: false } });
await expect.element(page.getByRole('link', { name: /benutzer/i })).not.toBeInTheDocument();
});
it('hides system link when canRunMaintenance is false', async () => {
render(Page, { data: { ...fullData, canRunMaintenance: false } });
await expect.element(page.getByRole('link', { name: /system/i })).not.toBeInTheDocument();
});
it('shows user count', async () => {
render(Page, { data: fullData });
await expect.element(page.getByText('4')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,8 @@
import { createApiClient } from '$lib/api.server';
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ fetch }) => {
const api = createApiClient(fetch);
const result = await api.GET('/api/users');
return { users: result.data ?? [] };
};

View File

@@ -0,0 +1,12 @@
<script lang="ts">
import UsersListPanel from './UsersListPanel.svelte';
let { data, children } = $props();
</script>
<UsersListPanel users={data.users} />
<!-- Detail panel -->
<div class="flex min-w-0 flex-1 flex-col overflow-hidden">
{@render children()}
</div>

View File

@@ -0,0 +1,7 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
</script>
<div class="flex flex-1 items-center justify-center p-8">
<p class="text-sm text-ink-3">{m.admin_users_select_prompt()}</p>
</div>

View File

@@ -0,0 +1,105 @@
<script lang="ts">
import { page } from '$app/state';
import { m } from '$lib/paraglide/messages.js';
type Group = {
id: string;
name: string;
permissions: string[];
};
type User = {
id: string;
username: string;
firstName: string | null;
lastName: string | null;
groups: Group[];
};
let { users }: { users: User[] } = $props();
let searchQuery = $state('');
const filtered = $derived(
searchQuery.trim() === ''
? users
: users.filter((u) =>
[u.username, u.firstName, u.lastName]
.filter(Boolean)
.some((v) => v!.toLowerCase().includes(searchQuery.toLowerCase()))
)
);
</script>
<div class="flex w-60 flex-shrink-0 flex-col overflow-hidden border-r border-line bg-surface">
<!-- Panel header -->
<div class="flex items-center justify-between border-b border-line px-3 py-2">
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_users_list_title()}
</span>
<a
href="/admin/users/new"
class="inline-flex items-center gap-1 rounded-sm px-2 py-1 text-xs font-medium text-ink-2 transition-colors hover:bg-muted hover:text-ink"
title={m.admin_btn_new_user()}
aria-label={m.admin_btn_new_user()}
>
<svg
class="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2.5"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
</svg>
{m.admin_btn_new_user()}
</a>
</div>
<!-- Search -->
<div class="border-b border-line px-3 py-2">
<input
type="search"
bind:value={searchQuery}
placeholder={m.admin_users_search_placeholder()}
class="w-full rounded-sm border border-line bg-surface px-2 py-1.5 text-sm text-ink placeholder:text-ink-3 focus:ring-1 focus:ring-primary focus:outline-none"
/>
</div>
<!-- Scrollable user list -->
<div class="flex-1 overflow-y-auto">
{#if filtered.length === 0}
<p class="px-4 py-6 text-center text-xs text-ink-3">
{m.admin_users_empty()}
</p>
{:else}
{#each filtered as user (user.id)}
{@const isActive = page.url.pathname.startsWith('/admin/users/' + user.id)}
{@const fullName =
[user.firstName, user.lastName].filter(Boolean).join(' ') || null}
<a
href="/admin/users/{user.id}"
aria-current={isActive ? 'page' : undefined}
class="block border-l-2 px-3 py-2.5 transition-colors {isActive
? 'border-primary bg-primary/10 dark:bg-primary/15'
: 'border-transparent hover:bg-muted'}"
>
<div class="text-sm font-bold text-ink">{user.username}</div>
{#if fullName}
<div class="mt-0.5 text-xs text-ink-3">{fullName}</div>
{/if}
{#if user.groups.length > 0}
<div class="mt-1 flex flex-wrap gap-1">
{#each user.groups as group (group.id)}
<span class="rounded-sm bg-muted px-1.5 py-0.5 text-[10px] text-ink-3">
{group.name}
</span>
{/each}
</div>
{/if}
</a>
{/each}
{/if}
</div>
</div>

View File

@@ -10,85 +10,74 @@ let { data, form } = $props();
const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string }) => g.id) ?? []);
</script>
<div class="mx-auto max-w-3xl px-4 py-8 sm:px-6 lg:px-8">
<a
href="/admin"
class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
>
<svg
class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Detail panel header -->
<div class="flex items-center border-b border-line px-5 py-3">
<h2 class="flex-1 font-sans text-sm font-bold text-ink">
{m.admin_user_edit_heading({ username: data.editUser.username })}
</h2>
</div>
<!-- Scrollable body -->
<div class="flex-1 overflow-y-auto px-5 py-5">
{#if form?.success}
<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
{m.admin_user_updated()}
</div>
{/if}
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
<form id="edit-user-form" method="POST" use:enhance class="space-y-5">
<!-- Profile card -->
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h3>
<UserProfileSection
firstName={data.editUser.firstName ?? ''}
lastName={data.editUser.lastName ?? ''}
birthDate={data.editUser.birthDate ?? ''}
email={data.editUser.email ?? ''}
contact={data.editUser.contact ?? ''}
/>
</div>
<!-- Groups card -->
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h3>
<UserGroupsSection groups={data.groups} selectedGroupIds={selectedGroupIds} />
</div>
<!-- Password card -->
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_label_new_password_optional()}
</h3>
<UserPasswordSection />
</div>
</form>
</div>
<!-- Docked footer -->
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
<a
href="/admin/users"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
{m.btn_back_to_overview()}
</a>
<h1 class="mb-6 font-serif text-3xl font-bold text-ink">
{m.admin_user_edit_heading({ username: data.editUser.username })}
</h1>
{#if form?.success}
<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
{m.admin_user_updated()}
</div>
{/if}
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
<form method="POST" use:enhance class="space-y-6">
<!-- Profile card -->
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h2>
<UserProfileSection
firstName={data.editUser.firstName ?? ''}
lastName={data.editUser.lastName ?? ''}
birthDate={data.editUser.birthDate ?? ''}
email={data.editUser.email ?? ''}
contact={data.editUser.contact ?? ''}
/>
</div>
<!-- Groups card -->
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h2>
<UserGroupsSection groups={data.groups} selectedGroupIds={selectedGroupIds} />
</div>
<!-- Password card -->
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_label_new_password_optional()}
</h2>
<UserPasswordSection />
</div>
<!-- Save bar -->
<div
class="sticky bottom-0 z-10 -mx-4 flex items-center justify-between border-t border-line bg-surface px-6 py-4 shadow-[0_-2px_8px_rgba(0,0,0,0.06)]"
{m.btn_cancel()}
</a>
<button
type="submit"
form="edit-user-form"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
<a
href="/admin"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
{m.btn_cancel()}
</a>
<button
type="submit"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
{m.btn_save()}
</button>
</div>
</form>
{m.btn_save()}
</button>
</div>
</div>

View File

@@ -110,11 +110,11 @@ describe('Admin edit user page rendering', () => {
});
});
it('cancel link points to /admin', async () => {
it('cancel link points to /admin/users', async () => {
render(Page, { data: baseData, form: null });
await expect
.element(page.getByRole('link', { name: /Abbrechen/i }))
.toHaveAttribute('href', '/admin');
.toHaveAttribute('href', '/admin/users');
});
it('renders the save button', async () => {

View File

@@ -0,0 +1,41 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { load } from './+layout.server';
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
import { createApiClient } from '$lib/api.server';
function mockApi(users: unknown[]) {
vi.mocked(createApiClient).mockReturnValue({
GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: users })
} as ReturnType<typeof createApiClient>);
}
beforeEach(() => vi.clearAllMocks());
describe('admin/users layout load', () => {
it('returns the users list', async () => {
mockApi([
{ id: 'u1', username: 'alice' },
{ id: 'u2', username: 'bob' }
]);
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
expect(result.users).toHaveLength(2);
expect(result.users[0].username).toBe('alice');
});
it('returns an empty array when the API returns nothing', async () => {
mockApi([]);
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
expect(result.users).toEqual([]);
});
it('calls GET /api/users', async () => {
const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] });
vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
typeof createApiClient
>);
await load({ fetch: vi.fn() as unknown as typeof fetch });
expect(mockGet).toHaveBeenCalledWith('/api/users');
});
});

View File

@@ -0,0 +1,95 @@
import { afterEach, describe, it, expect, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import UsersListPanel from './UsersListPanel.svelte';
vi.mock('$app/state', () => ({
page: { url: { pathname: '/admin/users/u1' } }
}));
afterEach(cleanup);
const users = [
{
id: 'u1',
username: 'reader',
firstName: 'Lea',
lastName: 'Leserin',
groups: [{ id: 'g1', name: 'Leser', permissions: ['READ_ALL'] }]
},
{
id: 'u2',
username: 'admin',
firstName: null,
lastName: null,
groups: [{ id: 'g2', name: 'Admins', permissions: ['ADMIN'] }]
}
];
describe('UsersListPanel — header', () => {
it('renders the panel title', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByText(/Alle Benutzer/i)).toBeInTheDocument();
});
it('renders a new-user link pointing to /admin/users/new', async () => {
render(UsersListPanel, { users });
await expect
.element(page.getByRole('link', { name: /neuer benutzer/i }))
.toHaveAttribute('href', '/admin/users/new');
});
it('renders a search input', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByRole('searchbox')).toBeInTheDocument();
});
});
describe('UsersListPanel — user items', () => {
it('renders each username', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByRole('link', { name: /reader/i })).toBeInTheDocument();
await expect.element(page.getByRole('link', { name: /admin/i })).toBeInTheDocument();
});
it('each user links to /admin/users/[id]', async () => {
const { container } = render(UsersListPanel, { users });
const links = container.querySelectorAll<HTMLAnchorElement>('a[href^="/admin/users/u"]');
expect(links.length).toBe(2);
expect(links[0].getAttribute('href')).toBe('/admin/users/u1');
expect(links[1].getAttribute('href')).toBe('/admin/users/u2');
});
it('shows full name as subtitle when available', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByText('Lea Leserin')).toBeInTheDocument();
});
it('shows group name chip', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByText('Leser', { exact: true })).toBeInTheDocument();
});
});
describe('UsersListPanel — active state', () => {
it('marks the active user link with aria-current=page', async () => {
render(UsersListPanel, { users });
await expect
.element(page.getByRole('link', { name: /reader/i }))
.toHaveAttribute('aria-current', 'page');
});
it('does not mark the inactive user link with aria-current', async () => {
render(UsersListPanel, { users });
await expect
.element(page.getByRole('link', { name: /admin/i }))
.not.toHaveAttribute('aria-current');
});
});
describe('UsersListPanel — empty state', () => {
it('shows empty state message when users array is empty', async () => {
render(UsersListPanel, { users: [] });
await expect.element(page.getByText(/keine benutzer/i)).toBeInTheDocument();
});
});

View File

@@ -40,6 +40,6 @@ export const actions: Actions = {
return fail(result.response.status, { error: getErrorMessage(code) });
}
throw redirect(303, '/admin');
throw redirect(303, '/admin/users');
}
};

View File

@@ -8,64 +8,57 @@ import AccountSection from './AccountSection.svelte';
let { data, form } = $props();
</script>
<div class="mx-auto max-w-3xl px-4 py-8 sm:px-6 lg:px-8">
<a
href="/admin"
class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
>
<svg
class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
{m.btn_back_to_overview()}
</a>
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Detail panel header -->
<div class="flex items-center border-b border-line px-5 py-3">
<h2 class="flex-1 font-sans text-sm font-bold text-ink">{m.admin_user_new_heading()}</h2>
</div>
<h1 class="mb-6 font-serif text-3xl font-bold text-ink">{m.admin_user_new_heading()}</h1>
<!-- Scrollable body -->
<div class="flex-1 overflow-y-auto px-5 py-5">
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<form method="POST" use:enhance class="space-y-5">
<AccountSection />
<form id="new-user-form" method="POST" use:enhance class="space-y-5">
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<AccountSection />
</div>
<!-- Profile -->
<h2 class="pt-2 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h2>
<UserProfileSection />
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h3>
<UserProfileSection />
</div>
<!-- Groups -->
<h2 class="pt-2 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h2>
<UserGroupsSection groups={data.groups} />
<!-- Save bar -->
<div
class="mt-4 flex items-center justify-between rounded-sm border border-line bg-surface px-6 py-4 shadow-sm"
>
<a
href="/admin"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
{m.btn_cancel()}
</a>
<button
type="submit"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
{m.btn_create()}
</button>
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h3>
<UserGroupsSection groups={data.groups} />
</div>
</form>
</div>
<!-- Docked footer -->
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
<a
href="/admin/users"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
{m.btn_cancel()}
</a>
<button
type="submit"
form="new-user-form"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
{m.btn_create()}
</button>
</div>
</div>

View File

@@ -33,18 +33,11 @@ describe('Admin new user page rendering', () => {
await expect.element(page.getByText('Admins')).toBeInTheDocument();
});
it('cancel link points to /admin', async () => {
it('cancel link points to /admin/users', async () => {
render(Page, { data: baseData, form: null });
await expect
.element(page.getByRole('link', { name: /Abbrechen/i }))
.toHaveAttribute('href', '/admin');
});
it('back link points to /admin', async () => {
render(Page, { data: baseData, form: null });
await expect
.element(page.getByRole('link', { name: /Zurück/i }))
.toHaveAttribute('href', '/admin');
.toHaveAttribute('href', '/admin/users');
});
it('renders the create button', async () => {