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.
This commit is contained in:
parent
b190835185
commit
9b1594e9f2
7 changed files with 681 additions and 0 deletions
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
90
web/src/pages/admin/AddUserForm.test.tsx
Normal file
90
web/src/pages/admin/AddUserForm.test.tsx
Normal file
|
|
@ -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(
|
||||
<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('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.')
|
||||
})
|
||||
94
web/src/pages/admin/AddUserForm.tsx
Normal file
94
web/src/pages/admin/AddUserForm.tsx
Normal file
|
|
@ -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 (
|
||||
<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)}
|
||||
/>
|
||||
<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>
|
||||
)
|
||||
}
|
||||
187
web/src/pages/admin/UserList.test.tsx
Normal file
187
web/src/pages/admin/UserList.test.tsx
Normal file
|
|
@ -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(
|
||||
<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('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)
|
||||
})
|
||||
224
web/src/pages/admin/UserList.tsx
Normal file
224
web/src/pages/admin/UserList.tsx
Normal file
|
|
@ -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 (
|
||||
<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)} />
|
||||
<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>
|
||||
)
|
||||
}
|
||||
8
web/src/pages/admin/password.ts
Normal file
8
web/src/pages/admin/password.ts
Normal 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
|
||||
}
|
||||
Loading…
Reference in a new issue