Merge pull request 'feat(web): users in the admin area (F3b)' (#73) from feat/admin-users into main

This commit is contained in:
squidd 2026-11-12 15:02:50 +01:00
commit fc499214b4
14 changed files with 878 additions and 4 deletions

View file

@ -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

View file

@ -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 }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
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')
})

51
web/src/api/users.ts Normal file
View file

@ -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<User>('/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<User>(`/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 }),
})
}

View file

@ -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)

View file

@ -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.",

View file

@ -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.",

View file

@ -0,0 +1,101 @@
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(
<QueryClientProvider client={client}>
<AddUserForm />
</QueryClientProvider>,
)
}
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('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()
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.')
})

View file

@ -0,0 +1,97 @@
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 (
<Section title={t('admin.users.addTitle')}>
<form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="user-email">{t('admin.users.email')}</Label>
<Input
id="user-email"
type="text"
inputMode="email"
value={email}
maxLength={MAX_EMAIL}
autoComplete="off"
autoCapitalize="off"
spellCheck={false}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="user-password">{t('admin.users.password')}</Label>
<Input
id="user-password"
type="password"
value={password}
autoComplete="new-password"
onChange={(e) => {
setPassword(e.target.value)
setTooShort(false)
}}
/>
<p className="text-sm text-muted-foreground">{t('admin.users.passwordHint')}</p>
</div>
<label className="flex min-h-11 items-center gap-3 font-semibold">
<input type="checkbox" checked={isAdmin} onChange={(e) => setIsAdmin(e.target.checked)} className="size-5 accent-primary" />
{t('admin.users.makeAdminCheck')}
</label>
{tooShort && (
<p role="alert" className="text-sm text-destructive">
{t('admin.users.passwordLength')}
</p>
)}
{create.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, create.error, ['admin.users.errors', 'admin.errors'])}
</p>
)}
<Button type="submit" disabled={!ready || create.isPending} className="self-start">
{t('admin.users.add')}
</Button>
</form>
</Section>
)
}

View file

@ -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

View file

@ -0,0 +1,199 @@
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(
<QueryClientProvider client={client}>
<UserList />
</QueryClientProvider>,
)
}
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('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()
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)
})

View file

@ -0,0 +1,229 @@
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 (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{body}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{t('admin.cancel')}
</Button>
<Button onClick={onConfirm}>{confirm}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
/**
* 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 (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<form onSubmit={submit} className="flex flex-col gap-4">
<DialogHeader>
<DialogTitle>{t('admin.users.resetTitle', { email: user.email })}</DialogTitle>
<DialogDescription>{t('admin.users.resetBody')}</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-2">
<Label htmlFor="reset-password">{t('admin.users.newPassword')}</Label>
<Input id="reset-password" type="password" autoComplete="new-password" value={password}
onChange={(e) => {
setPassword(e.target.value)
setTooShort(false)
}}
/>
<p className="text-sm text-muted-foreground">{t('admin.users.passwordHint')}</p>
</div>
{tooShort && (
<p role="alert" className="text-sm text-destructive">
{t('admin.users.resetPasswordLength')}
</p>
)}
{reset.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, reset.error, SCOPES)}
</p>
)}
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
{t('admin.cancel')}
</Button>
<Button type="submit" disabled={password === '' || reset.isPending}>
{t('admin.users.reset')}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
/**
* 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<User | null>(null)
const [resetting, setResetting] = useState<User | null>(null)
const [deleting, setDeleting] = useState<User | null>(null)
const [resetDone, setResetDone] = useState<string | null>(null)
const failure = setAdmin.error ?? remove.error
return (
<Section title={t('admin.users.title')}>
{users.isError ? (
<ErrorMessage error={users.error} onRetry={() => void users.refetch()} />
) : users.isPending ? (
<Loading />
) : users.data.length === 0 ? (
<EmptyMessage>{t('admin.users.empty')}</EmptyMessage>
) : (
<ul className="flex flex-col gap-3">
{users.data.map((user) => (
<li key={user.id} className="flex flex-wrap items-center gap-4 rounded-lg bg-card p-4 text-card-foreground">
<div className="flex min-w-40 flex-1 flex-wrap items-center gap-3">
<span className="text-lg font-bold break-all">{user.email}</span>
{user.is_admin && <span className="rounded-md bg-secondary px-2 py-0.5 text-sm font-semibold">{t('admin.users.admin')}</span>}
{user.id === me?.id && <span className="rounded-md bg-secondary px-2 py-0.5 text-sm font-semibold">{t('admin.users.you')}</span>}
</div>
{user.id !== me?.id && (
<div className="flex flex-wrap gap-2">
{user.is_admin ? (
<Button variant="outline" aria-label={t('admin.users.removeAdminOne', { email: user.email })} onClick={() => setDemoting(user)}>
{t('admin.users.removeAdmin')}
</Button>
) : (
<Button
variant="outline"
disabled={setAdmin.isPending}
aria-label={t('admin.users.makeAdminOne', { email: user.email })}
onClick={() => setAdmin.mutate({ id: user.id, is_admin: true })}
>
{t('admin.users.makeAdmin')}
</Button>
)}
<Button variant="outline" aria-label={t('admin.users.resetOne', { email: user.email })} onClick={() => setResetting(user)}>
{t('admin.users.reset')}
</Button>
<Button variant="outline" aria-label={t('admin.users.deleteOne', { email: user.email })} onClick={() => setDeleting(user)}>
{t('admin.users.delete')}
</Button>
</div>
)}
</li>
))}
</ul>
)}
{resetDone && (
<p role="status" className="text-sm text-muted-foreground">
{t('admin.users.resetDone', { email: resetDone })}
</p>
)}
{failure ? (
<p role="alert" className="text-sm text-destructive">
{errorText(t, failure, SCOPES)}
</p>
) : null}
{demoting && (
<Confirm
title={t('admin.users.removeAdminTitle', { email: demoting.email })}
body={t('admin.users.removeAdminBody')}
confirm={t('admin.users.removeAdminConfirm')}
onClose={() => setDemoting(null)}
onConfirm={() => {
setAdmin.mutate({ id: demoting.id, is_admin: false })
setDemoting(null)
}}
/>
)}
{deleting && (
<Confirm
title={t('admin.users.deleteTitle', { email: deleting.email })}
body={t('admin.users.deleteBody')}
confirm={t('admin.users.deleteConfirm')}
onClose={() => setDeleting(null)}
onConfirm={() => {
remove.mutate(deleting.id)
setDeleting(null)
}}
/>
)}
{resetting && (
<ResetDialog
key={resetting.id}
user={resetting}
onClose={() => setResetting(null)}
onDone={() => {
setResetDone(resetting.email)
setResetting(null)
}}
/>
)}
</Section>
)
}

View file

@ -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 (
<div className="flex flex-col gap-10">
<UserList />
<AddUserForm />
</div>
)
}

View file

@ -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
}

View file

@ -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: <Navigate to="/admin/libraries" replace /> },
{ path: 'libraries', element: <LibrariesPage /> },
{ path: 'users', element: <UsersPage /> },
],
},
{ path: '*', element: <NotFoundPage /> },