From b1908351856a129fe96fb1544b6cdd701de7cca3 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:55:26 +0100 Subject: [PATCH 1/4] feat(web): hooks for listing, creating, changing and deleting users Listing, creating, giving or taking the admin role, resetting a password and deleting, each refreshing the list when the list changes. --- web/src/api/users.test.tsx | 75 ++++++++++++++++++++++++++++++++++++++ web/src/api/users.ts | 51 ++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 web/src/api/users.test.tsx create mode 100644 web/src/api/users.ts diff --git a/web/src/api/users.test.tsx b/web/src/api/users.test.tsx new file mode 100644 index 0000000..cb4a97f --- /dev/null +++ b/web/src/api/users.test.tsx @@ -0,0 +1,75 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook, waitFor } from '@testing-library/react' +import type { ReactNode } from 'react' +import { expect, test } from 'vitest' +import { mockFetch } from '@/test/mockFetch' +import { useCreateUser, useDeleteUser, useResetPassword, useSetAdmin, useUsers } from './users' + +function setup() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => {children} + return { client, wrapper } +} + +const user = (id: number, is_admin = false) => ({ id, email: `u${id}@example.org`, is_admin }) +const none = () => new Response(null, { status: 204 }) +const json = (body: object, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) + +test('the users are listed, oldest first as the server sends them', async () => { + mockFetch({ 'GET /api/v1/users': () => ({ users: [user(1, true), user(2)] }) }) + const { result } = renderHook(() => useUsers(), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.data).toHaveLength(2)) + expect(result.current.data?.[0].email).toBe('u1@example.org') +}) + +test('creating sends the email, the password and the role, and the list is read again', async () => { + let users = [user(1, true)] + const { calls } = mockFetch({ + 'GET /api/v1/users': () => ({ users }), + 'POST /api/v1/users': ({ init }) => { + const body = JSON.parse(String(init.body)) + users = [...users, user(2, body.is_admin)] + return json(users[1], 201) + }, + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ list: useUsers(), create: useCreateUser() }), { wrapper }) + await waitFor(() => expect(result.current.list.data).toHaveLength(1)) + await act(() => result.current.create.mutateAsync({ email: 'new@example.org', password: 'correct horse', is_admin: true })) + await waitFor(() => expect(result.current.list.data).toHaveLength(2)) + expect(JSON.parse(String(calls.find((c) => c.key === 'POST /api/v1/users')?.init.body))).toEqual({ + email: 'new@example.org', + password: 'correct horse', + is_admin: true, + }) +}) + +test('giving or taking the admin role is a PATCH with the role only', async () => { + const { calls } = mockFetch({ 'PATCH /api/v1/users/2': () => user(2, true), 'GET /api/v1/users': () => ({ users: [] }) }) + const { result } = renderHook(() => useSetAdmin(), { wrapper: setup().wrapper }) + await act(() => result.current.mutateAsync({ id: 2, is_admin: true })) + await act(() => result.current.mutateAsync({ id: 2, is_admin: false })) + const bodies = calls.filter((c) => c.key === 'PATCH /api/v1/users/2').map((c) => JSON.parse(String(c.init.body))) + expect(bodies).toEqual([{ is_admin: true }, { is_admin: false }]) +}) + +test('resetting a password is a PUT with the new password, and the list is not read again', async () => { + const { calls } = mockFetch({ 'PUT /api/v1/users/2/password': none, 'GET /api/v1/users': () => ({ users: [] }) }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ list: useUsers(), reset: useResetPassword() }), { wrapper }) + await waitFor(() => expect(result.current.list.isSuccess).toBe(true)) + await act(() => result.current.reset.mutateAsync({ id: 2, password: 'a brand new one' })) + await new Promise((r) => setTimeout(r, 30)) + expect(JSON.parse(String(calls.find((c) => c.key === 'PUT /api/v1/users/2/password')?.init.body))).toEqual({ password: 'a brand new one' }) + expect(calls.filter((c) => c.key === 'GET /api/v1/users')).toHaveLength(1) +}) + +test('deleting removes that account and the list is read again', async () => { + const { calls } = mockFetch({ 'DELETE /api/v1/users/2': none, 'GET /api/v1/users': () => ({ users: [user(1, true)] }) }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ list: useUsers(), del: useDeleteUser() }), { wrapper }) + await waitFor(() => expect(result.current.list.isSuccess).toBe(true)) + await act(() => result.current.del.mutateAsync(2)) + await waitFor(() => expect(calls.filter((c) => c.key === 'GET /api/v1/users')).toHaveLength(2)) + expect(calls.map((c) => c.key)).toContain('DELETE /api/v1/users/2') +}) diff --git a/web/src/api/users.ts b/web/src/api/users.ts new file mode 100644 index 0000000..e11f486 --- /dev/null +++ b/web/src/api/users.ts @@ -0,0 +1,51 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api } from './client' +import type { components } from './schema' + +export type User = components['schemas']['User'] + +const USERS = ['users'] + +/** Every account, oldest first. Admins only. */ +export function useUsers() { + return useQuery({ + queryKey: USERS, + queryFn: () => api.get<{ users: User[] }>('/users'), + select: (data) => data.users, + }) +} + +export function useCreateUser() { + const client = useQueryClient() + return useMutation({ + mutationFn: (body: { email: string; password: string; is_admin: boolean }) => api.post('/users', body), + onSuccess: () => client.invalidateQueries({ queryKey: USERS }), + }) +} + +/** Gives or takes away the admin role. The last admin cannot lose it (`last_admin`). */ +export function useSetAdmin() { + const client = useQueryClient() + return useMutation({ + mutationFn: ({ id, is_admin }: { id: number; is_admin: boolean }) => api.patch(`/users/${id}`, { is_admin }), + onSuccess: () => client.invalidateQueries({ queryKey: USERS }), + }) +} + +/** + * Sets a new password and ends every session of that account. Nothing about the account changes, so the list + * is not read again. The password is in the mutation's variables until `reset()` is called: callers do that. + */ +export function useResetPassword() { + return useMutation({ + mutationFn: ({ id, password }: { id: number; password: string }) => api.put(`/users/${id}/password`, { password }), + }) +} + +export function useDeleteUser() { + const client = useQueryClient() + return useMutation({ + mutationFn: (id: number) => api.del(`/users/${id}`), + onSuccess: () => client.invalidateQueries({ queryKey: USERS }), + }) +} From 9b1594e9f287587ba7dbac54dcd6f21daca3314b Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:57:22 +0100 Subject: [PATCH 2/4] feat(web): the user list with its actions and the form to add a user Give the admin role at once, take it away or delete an account after a question, reset a password in a dialog that forgets it (and ends that person's sessions), and add an account by email. Your own row has no buttons, and the last admin cannot be changed: the page says so. --- web/src/i18n/locales/en.json | 39 ++++ web/src/i18n/locales/it.json | 39 ++++ web/src/pages/admin/AddUserForm.test.tsx | 90 +++++++++ web/src/pages/admin/AddUserForm.tsx | 94 ++++++++++ web/src/pages/admin/UserList.test.tsx | 187 +++++++++++++++++++ web/src/pages/admin/UserList.tsx | 224 +++++++++++++++++++++++ web/src/pages/admin/password.ts | 8 + 7 files changed, 681 insertions(+) create mode 100644 web/src/pages/admin/AddUserForm.test.tsx create mode 100644 web/src/pages/admin/AddUserForm.tsx create mode 100644 web/src/pages/admin/UserList.test.tsx create mode 100644 web/src/pages/admin/UserList.tsx create mode 100644 web/src/pages/admin/password.ts diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 2069fb4..f73850e 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -65,6 +65,7 @@ "sections": "Admin sections", "adminOnly": "Only admins can see this page.", "sectionLibraries": "Libraries", + "sectionUsers": "Users", "cancel": "Cancel", "save": "Save", "errors": { @@ -72,6 +73,44 @@ "no_libraries": "Add a library first.", "admin_required": "Only an admin can do this." }, + "users": { + "title": "Users", + "empty": "No users.", + "admin": "Admin", + "you": "You", + "makeAdmin": "Make admin", + "makeAdminOne": "Make {{email}} an admin", + "removeAdmin": "Remove admin", + "removeAdminOne": "Remove admin role from {{email}}", + "removeAdminTitle": "Remove the admin role from {{email}}?", + "removeAdminBody": "They will no longer be able to manage libraries, users or providers.", + "removeAdminConfirm": "Remove admin role", + "reset": "Reset password", + "resetOne": "Reset password for {{email}}", + "resetTitle": "Reset the password of {{email}}", + "resetBody": "The new password ends every session of this account. Tell the person the new password yourself: Sonda sends no mail.", + "newPassword": "New password", + "passwordHint": "8 to 256 characters.", + "resetPasswordLength": "The new password needs 8 to 256 characters.", + "resetDone": "Password reset. {{email}} was signed out everywhere.", + "delete": "Delete", + "deleteOne": "Delete {{email}}", + "deleteTitle": "Delete {{email}}?", + "deleteBody": "This removes the account and ends its sessions. It cannot be undone.", + "deleteConfirm": "Delete account", + "addTitle": "Add a user", + "email": "Email", + "password": "Password", + "makeAdminCheck": "Make this person an admin", + "add": "Add user", + "passwordLength": "The password needs 8 to 256 characters.", + "errors": { + "email_taken": "That email address is already used.", + "invalid_input": "Check the email address and the password.", + "last_admin": "This is the last admin, so it cannot be changed.", + "user_not_found": "This account does not exist any more." + } + }, "libraries": { "title": "Libraries", "empty": "No libraries yet. Add one below.", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 2ed3cd1..c1ead25 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -65,6 +65,7 @@ "sections": "Sezioni admin", "adminOnly": "Solo gli admin possono vedere questa pagina.", "sectionLibraries": "Librerie", + "sectionUsers": "Utenti", "cancel": "Annulla", "save": "Salva", "errors": { @@ -72,6 +73,44 @@ "no_libraries": "Aggiungi prima una libreria.", "admin_required": "Solo un admin può farlo." }, + "users": { + "title": "Utenti", + "empty": "Nessun utente.", + "admin": "Admin", + "you": "Tu", + "makeAdmin": "Rendi admin", + "makeAdminOne": "Rendi admin {{email}}", + "removeAdmin": "Togli admin", + "removeAdminOne": "Togli il ruolo admin a {{email}}", + "removeAdminTitle": "Togliere il ruolo admin a {{email}}?", + "removeAdminBody": "Non potrà più gestire librerie, utenti o provider.", + "removeAdminConfirm": "Togli ruolo admin", + "reset": "Reimposta password", + "resetOne": "Reimposta la password di {{email}}", + "resetTitle": "Reimposta la password di {{email}}", + "resetBody": "La nuova password chiude tutte le sessioni di questo account. Comunica tu la nuova password alla persona: Sonda non manda email.", + "newPassword": "Nuova password", + "passwordHint": "Da 8 a 256 caratteri.", + "resetPasswordLength": "La nuova password deve avere da 8 a 256 caratteri.", + "resetDone": "Password reimpostata. {{email}} è stato disconnesso ovunque.", + "delete": "Elimina", + "deleteOne": "Elimina {{email}}", + "deleteTitle": "Eliminare {{email}}?", + "deleteBody": "Questo rimuove l'account e chiude le sue sessioni. Non si può annullare.", + "deleteConfirm": "Elimina account", + "addTitle": "Aggiungi un utente", + "email": "Email", + "password": "Password", + "makeAdminCheck": "Rendi questa persona admin", + "add": "Aggiungi utente", + "passwordLength": "La password deve avere da 8 a 256 caratteri.", + "errors": { + "email_taken": "Questo indirizzo email è già usato.", + "invalid_input": "Controlla l'indirizzo email e la password.", + "last_admin": "Questo è l'ultimo admin, quindi non si può cambiare.", + "user_not_found": "Questo account non esiste più." + } + }, "libraries": { "title": "Librerie", "empty": "Ancora nessuna libreria. Aggiungine una qui sotto.", diff --git a/web/src/pages/admin/AddUserForm.test.tsx b/web/src/pages/admin/AddUserForm.test.tsx new file mode 100644 index 0000000..689ca1c --- /dev/null +++ b/web/src/pages/admin/AddUserForm.test.tsx @@ -0,0 +1,90 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { beforeEach, expect, test, vi } from 'vitest' +import { sessionStore } from '@/auth/session' +import { initI18n } from '@/i18n' +import { apiError, mockFetch } from '@/test/mockFetch' +import AddUserForm from './AddUserForm' + +const created = () => + new Response(JSON.stringify({ id: 9, email: 'new@example.org', is_admin: false }), { status: 201, headers: { 'Content-Type': 'application/json' } }) + +function renderForm() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + , + ) +} + +const email = () => screen.getByLabelText('Email') +const password = () => screen.getByLabelText('Password') +const admin = () => screen.getByRole('checkbox', { name: 'Make this person an admin' }) +const add = () => screen.getByRole('button', { name: 'Add user' }) + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } }) +}) + +test('the password is hidden and the browser is not asked to remember it', () => { + mockFetch({}) + renderForm() + expect(password()).toHaveAttribute('type', 'password') + expect(password()).toHaveAttribute('autocomplete', 'new-password') + expect(email()).toHaveAttribute('maxlength', '254') +}) + +test('nothing is sent while the email or the password is empty', async () => { + const { calls } = mockFetch({}) + renderForm() + expect(add()).toBeDisabled() + await userEvent.type(email(), 'new@example.org') + expect(add()).toBeDisabled() + expect(calls).toHaveLength(0) +}) + +test('a password of seven characters is refused here, with no request', async () => { + const { calls } = mockFetch({}) + renderForm() + await userEvent.type(email(), 'new@example.org') + await userEvent.type(password(), '1234567') + await userEvent.click(add()) + expect(await screen.findByRole('alert')).toHaveTextContent('The password needs 8 to 256 characters.') + expect(calls).toHaveLength(0) +}) + +test('adding sends the trimmed email, the password and the role, then empties the form', async () => { + const { calls } = mockFetch({ 'POST /api/v1/users': created }) + renderForm() + await userEvent.type(email(), ' new@example.org ') + await userEvent.type(password(), 'correct horse') + await userEvent.click(admin()) + await userEvent.click(add()) + await waitFor(() => expect(email()).toHaveValue('')) + expect(password()).toHaveValue('') + expect(admin()).not.toBeChecked() + expect(JSON.parse(String(calls[0].init.body))).toEqual({ email: 'new@example.org', password: 'correct horse', is_admin: true }) +}) + +test('an address that is already used is explained and what was typed stays', async () => { + mockFetch({ 'POST /api/v1/users': () => apiError(409, 'email_taken') }) + renderForm() + await userEvent.type(email(), 'new@example.org') + await userEvent.type(password(), 'correct horse') + await userEvent.click(add()) + expect(await screen.findByRole('alert')).toHaveTextContent('That email address is already used.') + expect(email()).toHaveValue('new@example.org') +}) + +test('a bad address is explained', async () => { + mockFetch({ 'POST /api/v1/users': () => apiError(400, 'invalid_input') }) + renderForm() + await userEvent.type(email(), 'not an address') + await userEvent.type(password(), 'correct horse') + await userEvent.click(add()) + expect(await screen.findByRole('alert')).toHaveTextContent('Check the email address and the password.') +}) diff --git a/web/src/pages/admin/AddUserForm.tsx b/web/src/pages/admin/AddUserForm.tsx new file mode 100644 index 0000000..9cc981c --- /dev/null +++ b/web/src/pages/admin/AddUserForm.tsx @@ -0,0 +1,94 @@ +import { useState, type FormEvent } from 'react' +import { useTranslation } from 'react-i18next' +import { useCreateUser } from '@/api/users' +import Section from '@/components/Section' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { errorText } from './errorText' +import { passwordLengthOk } from './password' + +/** What the server accepts as an address. */ +const MAX_EMAIL = 254 + +export default function AddUserForm() { + const { t } = useTranslation() + const create = useCreateUser() + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [isAdmin, setIsAdmin] = useState(false) + const [tooShort, setTooShort] = useState(false) + const ready = email.trim() !== '' && password !== '' + + function submit(event: FormEvent) { + event.preventDefault() + if (!ready) return + // The server counts bytes, not characters. + if (!passwordLengthOk(password)) { + setTooShort(true) + return + } + setTooShort(false) + create.mutate( + { email: email.trim(), password, is_admin: isAdmin }, + { + onSuccess: () => { + setEmail('') + setPassword('') + setIsAdmin(false) + // The password is kept by the mutation until it is reset: do not leave it there. + create.reset() + }, + }, + ) + } + + return ( +
+
+
+ + setEmail(e.target.value)} + /> +
+
+ + setPassword(e.target.value)} + /> +

{t('admin.users.passwordHint')}

+
+ + {tooShort && ( +

+ {t('admin.users.passwordLength')} +

+ )} + {create.isError && ( +

+ {errorText(t, create.error, ['admin.users.errors', 'admin.errors'])} +

+ )} + +
+
+ ) +} diff --git a/web/src/pages/admin/UserList.test.tsx b/web/src/pages/admin/UserList.test.tsx new file mode 100644 index 0000000..64039c7 --- /dev/null +++ b/web/src/pages/admin/UserList.test.tsx @@ -0,0 +1,187 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { beforeEach, expect, test, vi } from 'vitest' +import { sessionStore } from '@/auth/session' +import { initI18n } from '@/i18n' +import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch' +import UserList from './UserList' + +const none = () => new Response(null, { status: 204 }) +const user = (id: number, email: string, is_admin = false) => ({ id, email, is_admin }) +const USERS = [user(1, 'tom@example.org', true), user(2, 'ann@example.org'), user(3, 'bob@example.org', true), user(4, 'old-name')] + +function renderList() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + , + ) +} + +function routes(over: MockRoutes = {}): MockRoutes { + return { 'GET /api/v1/users': () => ({ users: USERS }), ...over } +} + +const row = async (email: string) => (await screen.findByText(email)).closest('li') as HTMLElement +const calledWith = (calls: RecordedCall[], key: string) => calls.filter((c) => c.key === key) + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } }) +}) + +test('every account is listed, an old one by the name it has, with who is an admin and which one is you', async () => { + mockFetch(routes()) + renderList() + expect(await row('ann@example.org')).not.toHaveTextContent('Admin') + expect(await row('bob@example.org')).toHaveTextContent('Admin') + expect(await row('old-name')).toBeInTheDocument() + const me = await row('tom@example.org') + expect(me).toHaveTextContent('Admin') + expect(me).toHaveTextContent('You') +}) + +test('your own account has no buttons: you cannot lock yourself out from here', async () => { + mockFetch(routes()) + renderList() + const me = await row('tom@example.org') + expect(within(me).queryAllByRole('button')).toHaveLength(0) +}) + +test('a failure to read the list is said in words with a way to try again', async () => { + mockFetch(routes({ 'GET /api/v1/users': () => apiError(500, 'internal') })) + renderList() + const alert = await screen.findByRole('alert') + expect(within(alert).getByRole('button', { name: 'Try again' })).toBeInTheDocument() +}) + +test('"Make admin" gives the role at once, with no question', async () => { + const { calls } = mockFetch(routes({ 'PATCH /api/v1/users/2': () => user(2, 'ann@example.org', true) })) + renderList() + await userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Make ann@example.org an admin' })) + await waitFor(() => expect(calledWith(calls, 'PATCH /api/v1/users/2')).toHaveLength(1)) + expect(JSON.parse(String(calledWith(calls, 'PATCH /api/v1/users/2')[0].init.body))).toEqual({ is_admin: true }) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() +}) + +test('taking the role away asks first, and nothing is sent until the answer is yes', async () => { + const { calls } = mockFetch(routes({ 'PATCH /api/v1/users/3': () => user(3, 'bob@example.org') })) + renderList() + await userEvent.click(within(await row('bob@example.org')).getByRole('button', { name: 'Remove admin role from bob@example.org' })) + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent('Remove the admin role from bob@example.org?') + expect(calledWith(calls, 'PATCH /api/v1/users/3')).toHaveLength(0) + + await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })) + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) + expect(calledWith(calls, 'PATCH /api/v1/users/3')).toHaveLength(0) + + await userEvent.click(within(await row('bob@example.org')).getByRole('button', { name: 'Remove admin role from bob@example.org' })) + await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Remove admin role' })) + await waitFor(() => expect(calledWith(calls, 'PATCH /api/v1/users/3')).toHaveLength(1)) + expect(JSON.parse(String(calledWith(calls, 'PATCH /api/v1/users/3')[0].init.body))).toEqual({ is_admin: false }) +}) + +test('the last admin cannot lose the role, and the page says so', async () => { + mockFetch(routes({ 'PATCH /api/v1/users/3': () => apiError(409, 'last_admin') })) + renderList() + await userEvent.click(within(await row('bob@example.org')).getByRole('button', { name: 'Remove admin role from bob@example.org' })) + await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Remove admin role' })) + expect(await screen.findByRole('alert')).toHaveTextContent('This is the last admin, so it cannot be changed.') +}) + +test('resetting a password asks for the new one, and a short one is refused without a request', async () => { + const { calls } = mockFetch(routes({ 'PUT /api/v1/users/2/password': none })) + renderList() + await userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Reset password for ann@example.org' })) + const dialog = await screen.findByRole('dialog') + const field = within(dialog).getByLabelText('New password') + expect(field).toHaveAttribute('type', 'password') + expect(field).toHaveAttribute('autocomplete', 'new-password') + await userEvent.type(field, '1234567') + await userEvent.click(within(dialog).getByRole('button', { name: 'Reset password' })) + expect(await within(dialog).findByRole('alert')).toHaveTextContent('The new password needs 8 to 256 characters.') + expect(calledWith(calls, 'PUT /api/v1/users/2/password')).toHaveLength(0) +}) + +test('a password longer than 256 bytes is refused without a request', async () => { + const { calls } = mockFetch(routes({ 'PUT /api/v1/users/2/password': none })) + renderList() + await userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Reset password for ann@example.org' })) + const dialog = await screen.findByRole('dialog') + await userEvent.click(within(dialog).getByLabelText('New password')) + await userEvent.paste('x'.repeat(257)) + await userEvent.click(within(dialog).getByRole('button', { name: 'Reset password' })) + expect(await within(dialog).findByRole('alert')).toBeInTheDocument() + expect(calledWith(calls, 'PUT /api/v1/users/2/password')).toHaveLength(0) +}) + +test('a good password is sent, the dialog closes and says that person was signed out everywhere', async () => { + const { calls } = mockFetch(routes({ 'PUT /api/v1/users/2/password': none })) + renderList() + await userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Reset password for ann@example.org' })) + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent('ends every session of this account') + await userEvent.type(within(dialog).getByLabelText('New password'), 'a brand new one') + await userEvent.click(within(dialog).getByRole('button', { name: 'Reset password' })) + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) + expect(JSON.parse(String(calledWith(calls, 'PUT /api/v1/users/2/password')[0].init.body))).toEqual({ password: 'a brand new one' }) + expect(screen.getByRole('status')).toHaveTextContent('Password reset. ann@example.org was signed out everywhere.') +}) + +test('the password is gone from the page when the dialog is opened again', async () => { + mockFetch(routes({ 'PUT /api/v1/users/2/password': none })) + renderList() + const open = async () => userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Reset password for ann@example.org' })) + await open() + await userEvent.type(within(await screen.findByRole('dialog')).getByLabelText('New password'), 'a brand new one') + await userEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Reset password' })) + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) + await open() + expect(within(await screen.findByRole('dialog')).getByLabelText('New password')).toHaveValue('') +}) + +test('deleting asks first, and says it cannot be undone', async () => { + const { calls } = mockFetch(routes({ 'DELETE /api/v1/users/2': none })) + renderList() + await userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Delete ann@example.org' })) + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent('Delete ann@example.org?') + expect(dialog).toHaveTextContent('cannot be undone') + expect(calledWith(calls, 'DELETE /api/v1/users/2')).toHaveLength(0) + await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })) + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) + expect(calledWith(calls, 'DELETE /api/v1/users/2')).toHaveLength(0) +}) + +test('confirming deletes the account and it leaves the list', async () => { + let users = USERS + mockFetch( + routes({ + 'GET /api/v1/users': () => ({ users }), + 'DELETE /api/v1/users/2': () => { + users = users.filter((u) => u.id !== 2) + return none() + }, + }), + ) + renderList() + await userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Delete ann@example.org' })) + await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete account' })) + await waitFor(() => expect(screen.queryByText('ann@example.org')).not.toBeInTheDocument()) + expect(screen.getByText('bob@example.org')).toBeInTheDocument() +}) + +test.each([ + [409, 'last_admin', 'This is the last admin, so it cannot be changed.'], + [404, 'user_not_found', 'This account does not exist any more.'], +])('a deletion refused with %i %s is explained', async (status, code, text) => { + mockFetch(routes({ 'DELETE /api/v1/users/3': () => apiError(status, code) })) + renderList() + await userEvent.click(within(await row('bob@example.org')).getByRole('button', { name: 'Delete bob@example.org' })) + await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete account' })) + expect(await screen.findByRole('alert')).toHaveTextContent(text) +}) diff --git a/web/src/pages/admin/UserList.tsx b/web/src/pages/admin/UserList.tsx new file mode 100644 index 0000000..1d4d08a --- /dev/null +++ b/web/src/pages/admin/UserList.tsx @@ -0,0 +1,224 @@ +import { useState, type FormEvent } from 'react' +import { useTranslation } from 'react-i18next' +import { useSession } from '@/auth/session' +import { useDeleteUser, useResetPassword, useSetAdmin, useUsers, type User } from '@/api/users' +import Section from '@/components/Section' +import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { errorText } from './errorText' +import { passwordLengthOk } from './password' + +const SCOPES = ['admin.users.errors', 'admin.errors'] + +/** A question with two answers, for what cannot be taken back or takes something away. */ +function Confirm({ + title, + body, + confirm, + onConfirm, + onClose, +}: { + title: string + body: string + confirm: string + onConfirm: () => void + onClose: () => void +}) { + const { t } = useTranslation() + return ( + !open && onClose()}> + + + {title} + {body} + + + + + + + + ) +} + +/** + * Asks for the new password. It lives only inside this dialog: closing it forgets it, and the mutation that + * holds it is reset as soon as it worked. + */ +function ResetDialog({ user, onClose, onDone }: { user: User; onClose: () => void; onDone: () => void }) { + const { t } = useTranslation() + const reset = useResetPassword() + const [password, setPassword] = useState('') + const [tooShort, setTooShort] = useState(false) + + function submit(event: FormEvent) { + event.preventDefault() + if (!passwordLengthOk(password)) { + setTooShort(true) + return + } + setTooShort(false) + reset.mutate( + { id: user.id, password }, + { + onSuccess: () => { + reset.reset() + onDone() + }, + }, + ) + } + + return ( + !open && onClose()}> + +
+ + {t('admin.users.resetTitle', { email: user.email })} + {t('admin.users.resetBody')} + +
+ + setPassword(e.target.value)} /> +

{t('admin.users.passwordHint')}

+
+ {tooShort && ( +

+ {t('admin.users.resetPasswordLength')} +

+ )} + {reset.isError && ( +

+ {errorText(t, reset.error, SCOPES)} +

+ )} + + + + +
+
+
+ ) +} + +/** + * The accounts, each with what an admin can do to it. Your own account has no buttons: demoting or deleting + * yourself would lock you out of this very page, and your password is changed in Settings. + */ +export default function UserList() { + const { t } = useTranslation() + const { user: me } = useSession() + const users = useUsers() + const setAdmin = useSetAdmin() + const remove = useDeleteUser() + const [demoting, setDemoting] = useState(null) + const [resetting, setResetting] = useState(null) + const [deleting, setDeleting] = useState(null) + const [resetDone, setResetDone] = useState(null) + const failure = setAdmin.error ?? remove.error + + return ( +
+ {users.isError ? ( + void users.refetch()} /> + ) : users.isPending ? ( + + ) : users.data.length === 0 ? ( + {t('admin.users.empty')} + ) : ( +
    + {users.data.map((user) => ( +
  • +
    + {user.email} + {user.is_admin && {t('admin.users.admin')}} + {user.id === me?.id && {t('admin.users.you')}} +
    + {user.id !== me?.id && ( +
    + {user.is_admin ? ( + + ) : ( + + )} + + +
    + )} +
  • + ))} +
+ )} + + {resetDone && ( +

+ {t('admin.users.resetDone', { email: resetDone })} +

+ )} + {failure ? ( +

+ {errorText(t, failure, SCOPES)} +

+ ) : null} + + {demoting && ( + setDemoting(null)} + onConfirm={() => { + setAdmin.mutate({ id: demoting.id, is_admin: false }) + setDemoting(null) + }} + /> + )} + {deleting && ( + setDeleting(null)} + onConfirm={() => { + remove.mutate(deleting.id) + setDeleting(null) + }} + /> + )} + {resetting && ( + setResetting(null)} + onDone={() => { + setResetDone(resetting.email) + setResetting(null) + }} + /> + )} +
+ ) +} diff --git a/web/src/pages/admin/password.ts b/web/src/pages/admin/password.ts new file mode 100644 index 0000000..39fdb9c --- /dev/null +++ b/web/src/pages/admin/password.ts @@ -0,0 +1,8 @@ +/** What the server accepts as a password: 8 to 256 bytes of UTF-8 (it counts bytes, not characters). */ +export const MIN_PASSWORD_BYTES = 8 +export const MAX_PASSWORD_BYTES = 256 + +export function passwordLengthOk(password: string): boolean { + const bytes = new TextEncoder().encode(password).length + return bytes >= MIN_PASSWORD_BYTES && bytes <= MAX_PASSWORD_BYTES +} From 52569a0f8dd60a2dec44915800341d5b63505372 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:58:01 +0100 Subject: [PATCH 3/4] feat(web): a Users section in the admin area Opens at /admin/users next to Libraries, for admins only; anyone else gets the notice and the server is not asked. README says what the admin area covers. --- README.md | 6 +++--- web/src/components/layout/Shell.test.tsx | 19 +++++++++++++++++++ web/src/pages/admin/AdminLayout.tsx | 5 ++++- web/src/pages/admin/UsersPage.tsx | 12 ++++++++++++ web/src/router.tsx | 2 ++ 5 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 web/src/pages/admin/UsersPage.tsx diff --git a/README.md b/README.md index d359716..f13821d 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr ## What is not there yet -Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and its admin area only covers libraries and scanning so far (users, providers and the bulk jobs are still API-only). +Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and its admin area covers libraries, scanning and users so far (providers and the bulk jobs are still API-only). ## Requirements @@ -328,9 +328,9 @@ npm install SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda ``` -What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. +What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. -More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). The rest of the admin screens (users, providers, bulk jobs) and serving the app from the binary come later. +More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). The rest of the admin screens (providers, bulk jobs) and serving the app from the binary come later. ## Development diff --git a/web/src/components/layout/Shell.test.tsx b/web/src/components/layout/Shell.test.tsx index 6f19e0b..18cfb67 100644 --- a/web/src/components/layout/Shell.test.tsx +++ b/web/src/components/layout/Shell.test.tsx @@ -53,6 +53,25 @@ test('the Admin link opens the libraries and stays current inside the admin area expect(within(mainNav()).getByRole('link', { name: 'Admin' })).toHaveAttribute('aria-current', 'page') }) +test('the admin area has a Users section next to Libraries', async () => { + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } }) + mockFetch({ ...adminRoutes, 'GET /api/v1/users': () => ({ users: [{ id: 1, email: 'tom@example.org', is_admin: true }] }) }) + renderAt('/admin/users') + expect(await screen.findByRole('region', { name: 'Users' })).toBeInTheDocument() + const sections = within(screen.getByRole('navigation', { name: 'Admin sections' })) + expect(sections.getByRole('link', { name: 'Users' })).toHaveAttribute('aria-current', 'page') + expect(sections.getByRole('link', { name: 'Libraries' })).not.toHaveAttribute('aria-current') +}) + +test('someone who is not an admin who opens the users address gets a notice and no request', async () => { + sessionStore.setState({ status: 'authenticated', user: { id: 2, email: 'ann@example.org', is_admin: false } }) + const { calls } = mockFetch({ 'GET /api/v1/users': () => ({ users: [] }) }) + renderAt('/admin/users') + expect(screen.getByText('Only admins can see this page.')).toBeInTheDocument() + await new Promise((r) => setTimeout(r, 30)) + expect(calls).toHaveLength(0) +}) + test('someone who is not an admin who opens the admin address gets a notice and no request', async () => { sessionStore.setState({ status: 'authenticated', user: { id: 2, email: 'ann@example.org', is_admin: false } }) const { calls } = mockFetch(adminRoutes) diff --git a/web/src/pages/admin/AdminLayout.tsx b/web/src/pages/admin/AdminLayout.tsx index 2fea6b1..fed5036 100644 --- a/web/src/pages/admin/AdminLayout.tsx +++ b/web/src/pages/admin/AdminLayout.tsx @@ -5,7 +5,10 @@ import { EmptyMessage } from '@/components/Status' import { cn } from '@/lib/utils' /** The sections of the admin area; each is a route under `/admin`. */ -const SECTIONS = [{ to: '/admin/libraries', key: 'admin.sectionLibraries' }] +const SECTIONS = [ + { to: '/admin/libraries', key: 'admin.sectionLibraries' }, + { to: '/admin/users', key: 'admin.sectionUsers' }, +] /** * The frame of the admin area. Only an admin gets the sections: anyone else gets a notice, and since the diff --git a/web/src/pages/admin/UsersPage.tsx b/web/src/pages/admin/UsersPage.tsx new file mode 100644 index 0000000..1f1a505 --- /dev/null +++ b/web/src/pages/admin/UsersPage.tsx @@ -0,0 +1,12 @@ +import AddUserForm from './AddUserForm' +import UserList from './UserList' + +/** The accounts and the form to add one. */ +export default function UsersPage() { + return ( +
+ + +
+ ) +} diff --git a/web/src/router.tsx b/web/src/router.tsx index cf66f97..328d198 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -8,6 +8,7 @@ import DiscoverPage from '@/pages/DiscoverPage' import HomePage from '@/pages/HomePage' import AdminLayout from '@/pages/admin/AdminLayout' import LibrariesPage from '@/pages/admin/LibrariesPage' +import UsersPage from '@/pages/admin/UsersPage' import NotFoundPage from '@/pages/NotFoundPage' import SearchPage from '@/pages/SearchPage' import SettingsPage from '@/pages/SettingsPage' @@ -32,6 +33,7 @@ export const routes: RouteObject[] = [ children: [ { index: true, element: }, { path: 'libraries', element: }, + { path: 'users', element: }, ], }, { path: '*', element: }, From a39c0f77196e6dd1917646d91a2d710a44e182cd Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:59:37 +0100 Subject: [PATCH 4/4] fix(web): clear the short-password complaint when the password is changed Found in a real browser: after the complaint, typing a valid password left it on screen until the next submit. Same in the reset dialog and the add form. --- web/src/pages/admin/AddUserForm.test.tsx | 11 +++++++++++ web/src/pages/admin/AddUserForm.tsx | 5 ++++- web/src/pages/admin/UserList.test.tsx | 12 ++++++++++++ web/src/pages/admin/UserList.tsx | 7 ++++++- 4 files changed, 33 insertions(+), 2 deletions(-) diff --git a/web/src/pages/admin/AddUserForm.test.tsx b/web/src/pages/admin/AddUserForm.test.tsx index 689ca1c..28e1ff6 100644 --- a/web/src/pages/admin/AddUserForm.test.tsx +++ b/web/src/pages/admin/AddUserForm.test.tsx @@ -57,6 +57,17 @@ test('a password of seven characters is refused here, with no request', async () expect(calls).toHaveLength(0) }) +test('the complaint about a short password goes away as soon as the password is changed', async () => { + mockFetch({}) + renderForm() + await userEvent.type(email(), 'new@example.org') + await userEvent.type(password(), '1234567') + await userEvent.click(add()) + expect(await screen.findByRole('alert')).toBeInTheDocument() + await userEvent.type(password(), '8') + expect(screen.queryByRole('alert')).not.toBeInTheDocument() +}) + test('adding sends the trimmed email, the password and the role, then empties the form', async () => { const { calls } = mockFetch({ 'POST /api/v1/users': created }) renderForm() diff --git a/web/src/pages/admin/AddUserForm.tsx b/web/src/pages/admin/AddUserForm.tsx index 9cc981c..623ce86 100644 --- a/web/src/pages/admin/AddUserForm.tsx +++ b/web/src/pages/admin/AddUserForm.tsx @@ -67,7 +67,10 @@ export default function AddUserForm() { type="password" value={password} autoComplete="new-password" - onChange={(e) => setPassword(e.target.value)} + onChange={(e) => { + setPassword(e.target.value) + setTooShort(false) + }} />

{t('admin.users.passwordHint')}

diff --git a/web/src/pages/admin/UserList.test.tsx b/web/src/pages/admin/UserList.test.tsx index 64039c7..727541c 100644 --- a/web/src/pages/admin/UserList.test.tsx +++ b/web/src/pages/admin/UserList.test.tsx @@ -107,6 +107,18 @@ test('resetting a password asks for the new one, and a short one is refused with expect(calledWith(calls, 'PUT /api/v1/users/2/password')).toHaveLength(0) }) +test('the complaint about a short password goes away as soon as the password is changed', async () => { + mockFetch(routes({ 'PUT /api/v1/users/2/password': none })) + renderList() + await userEvent.click(within(await row('ann@example.org')).getByRole('button', { name: 'Reset password for ann@example.org' })) + const dialog = await screen.findByRole('dialog') + await userEvent.type(within(dialog).getByLabelText('New password'), '1234567') + await userEvent.click(within(dialog).getByRole('button', { name: 'Reset password' })) + expect(await within(dialog).findByRole('alert')).toBeInTheDocument() + await userEvent.type(within(dialog).getByLabelText('New password'), '8') + expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument() +}) + test('a password longer than 256 bytes is refused without a request', async () => { const { calls } = mockFetch(routes({ 'PUT /api/v1/users/2/password': none })) renderList() diff --git a/web/src/pages/admin/UserList.tsx b/web/src/pages/admin/UserList.tsx index 1d4d08a..a3479d5 100644 --- a/web/src/pages/admin/UserList.tsx +++ b/web/src/pages/admin/UserList.tsx @@ -84,7 +84,12 @@ function ResetDialog({ user, onClose, onDone }: { user: User; onClose: () => voi
- setPassword(e.target.value)} /> + { + setPassword(e.target.value) + setTooShort(false) + }} + />

{t('admin.users.passwordHint')}

{tooShort && (