SettingsPageUsersWiring.test.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /**
  2. * Settings > Users: user and group management and "disable authentication"
  3. * send the request for the row/choice that was clicked, cancelling a
  4. * destructive dialog sends nothing, and buttons follow the permissions.
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import { screen, waitFor, within } from '@testing-library/react';
  8. import userEvent from '@testing-library/user-event';
  9. import { http, HttpResponse } from 'msw';
  10. import { render } from '../utils';
  11. import { server } from '../mocks/server';
  12. import { setAuthToken } from '../../api/client';
  13. import { SettingsPage } from '../../pages/SettingsPage';
  14. type Captured = { method: string; path: string; search: string; body: unknown };
  15. let captured: Captured[];
  16. let mePermissions: string[];
  17. let meIsAdmin: boolean;
  18. let itemCounts: { archives: number; queue_items: number; library_files: number };
  19. const USERS = [
  20. { id: 1, username: 'admin', email: null, role: 'admin', is_admin: true, is_active: true, auth_source: 'local', groups: [{ id: 1, name: 'Administrators' }], created_at: '2026-01-01T00:00:00Z' },
  21. { id: 2, username: 'alice', email: 'alice@example.com', role: 'user', is_admin: false, is_active: true, auth_source: 'local', groups: [{ id: 4, name: 'Farm crew' }], created_at: '2026-01-01T00:00:00Z' },
  22. { id: 3, username: 'bob', email: null, role: 'user', is_admin: false, is_active: true, auth_source: 'local', groups: [], created_at: '2026-01-01T00:00:00Z' },
  23. ];
  24. const GROUPS = [
  25. { id: 1, name: 'Administrators', description: null, is_system: true, permissions: [], user_count: 1, created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z' },
  26. { id: 4, name: 'Farm crew', description: null, is_system: false, permissions: [], user_count: 1, created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z' },
  27. { id: 6, name: 'Night shift', description: null, is_system: false, permissions: [], user_count: 0, created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z' },
  28. ];
  29. async function capture(request: Request) {
  30. const text = await request.text();
  31. const url = new URL(request.url);
  32. captured.push({ method: request.method, path: url.pathname, search: url.search, body: text ? JSON.parse(text) : null });
  33. }
  34. const writes = () => captured.filter((c) => c.method !== 'GET');
  35. function userRow(username: string): HTMLElement {
  36. const name = screen
  37. .getAllByText(username)
  38. .find((el) => el.tagName === 'P' && el.className.includes('truncate') && el.closest('div.py-3'));
  39. if (!name) throw new Error(`user row ${username} not found`);
  40. return name.closest('div.py-3') as HTMLElement;
  41. }
  42. function groupRow(name: string): HTMLElement {
  43. const label = screen
  44. .getAllByText(name)
  45. .find((el) => el.tagName === 'SPAN' && el.className === 'text-white font-medium' && el.closest('div.py-3'));
  46. if (!label) throw new Error(`group row ${name} not found`);
  47. return label.closest('div.py-3') as HTMLElement;
  48. }
  49. async function openUsersTab() {
  50. window.history.replaceState({}, '', '/settings?tab=users');
  51. render(<SettingsPage />);
  52. await screen.findByText('alice');
  53. }
  54. beforeEach(() => {
  55. captured = [];
  56. meIsAdmin = true;
  57. mePermissions = ['settings:read', 'users:read', 'users:create', 'users:update', 'users:delete', 'groups:read', 'groups:delete'];
  58. itemCounts = { archives: 2, queue_items: 0, library_files: 1 };
  59. setAuthToken('test-token', 'session');
  60. server.use(
  61. http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
  62. http.get('*/api/v1/auth/me', () =>
  63. HttpResponse.json({ ...USERS[0], is_admin: meIsAdmin, permissions: mePermissions }),
  64. ),
  65. http.get('*/api/v1/users/', () => HttpResponse.json(USERS)),
  66. http.get('*/api/v1/groups/', () => HttpResponse.json(GROUPS)),
  67. http.get('*/api/v1/users/:id/items-count', () => HttpResponse.json(itemCounts)),
  68. http.post('*/api/v1/users/', async ({ request }) => {
  69. await capture(request);
  70. return HttpResponse.json(USERS[2]);
  71. }),
  72. http.patch('*/api/v1/users/:id', async ({ request }) => {
  73. await capture(request);
  74. return HttpResponse.json(USERS[1]);
  75. }),
  76. http.delete('*/api/v1/users/:id', async ({ request }) => {
  77. await capture(request);
  78. return new HttpResponse(null, { status: 204 });
  79. }),
  80. http.delete('*/api/v1/groups/:id', async ({ request }) => {
  81. await capture(request);
  82. return new HttpResponse(null, { status: 204 });
  83. }),
  84. http.post('*/api/v1/auth/disable', async ({ request }) => {
  85. await capture(request);
  86. return HttpResponse.json({ message: 'ok', auth_enabled: false });
  87. }),
  88. );
  89. });
  90. afterEach(() => {
  91. setAuthToken(null);
  92. window.history.replaceState({}, '', '/');
  93. });
  94. describe('SettingsPage users & groups wiring', () => {
  95. it('create user sends username, password and the ticked group ids', async () => {
  96. const user = userEvent.setup();
  97. await openUsersTab();
  98. await user.click(screen.getByRole('button', { name: /add user/i }));
  99. await user.type(screen.getByPlaceholderText('Enter username'), 'carol');
  100. await user.type(screen.getByPlaceholderText('Enter password'), 'Test-password-1');
  101. await user.type(screen.getByPlaceholderText('Confirm password'), 'Test-password-1');
  102. const modal = screen.getByPlaceholderText('Enter username').closest('div.space-y-3') as HTMLElement;
  103. await user.click(within(modal).getByRole('checkbox', { name: /night shift/i }));
  104. await user.click(screen.getByRole('button', { name: /create user/i }));
  105. await waitFor(() => expect(writes()).toHaveLength(1));
  106. expect(writes()[0]).toMatchObject({ method: 'POST', path: '/api/v1/users/' });
  107. expect(writes()[0].body).toEqual({
  108. username: 'carol',
  109. password: 'Test-password-1',
  110. role: 'user',
  111. group_ids: [6],
  112. });
  113. });
  114. it('create user is blocked while the passwords differ', async () => {
  115. const user = userEvent.setup();
  116. await openUsersTab();
  117. await user.click(screen.getByRole('button', { name: /add user/i }));
  118. await user.type(screen.getByPlaceholderText('Enter username'), 'carol');
  119. await user.type(screen.getByPlaceholderText('Enter password'), 'Test-password-1');
  120. await user.type(screen.getByPlaceholderText('Confirm password'), 'Test-password-2');
  121. const create = screen.getByRole('button', { name: /create user/i });
  122. expect(create).toBeDisabled();
  123. await user.click(create);
  124. expect(writes()).toHaveLength(0);
  125. });
  126. it('edit user PATCHes that user without a password when it is left blank', async () => {
  127. const user = userEvent.setup();
  128. await openUsersTab();
  129. const [editBtn] = within(userRow('alice')).getAllByRole('button');
  130. await user.click(editBtn);
  131. const name = await screen.findByDisplayValue('alice');
  132. await user.clear(name);
  133. await user.type(name, 'alice2');
  134. await user.click(screen.getByRole('button', { name: /save changes/i }));
  135. await waitFor(() => expect(writes()).toHaveLength(1));
  136. expect(writes()[0]).toMatchObject({ method: 'PATCH', path: '/api/v1/users/2' });
  137. expect(writes()[0].body).toEqual({
  138. username: 'alice2',
  139. email: 'alice@example.com',
  140. role: 'user',
  141. group_ids: [4],
  142. });
  143. expect(writes()[0].body).not.toHaveProperty('password');
  144. });
  145. it('edit user with the email field emptied sends an empty email, which removes it', async () => {
  146. const user = userEvent.setup();
  147. await openUsersTab();
  148. const [editBtn] = within(userRow('alice')).getAllByRole('button');
  149. await user.click(editBtn);
  150. await user.clear(await screen.findByDisplayValue('alice@example.com'));
  151. await user.click(screen.getByRole('button', { name: /save changes/i }));
  152. await waitFor(() => expect(writes()).toHaveLength(1));
  153. expect(writes()[0]).toMatchObject({ method: 'PATCH', path: '/api/v1/users/2' });
  154. expect(writes()[0].body).toMatchObject({ email: '' });
  155. });
  156. it('delete user with items: "delete items" choice sends delete_items=true for that user', async () => {
  157. const user = userEvent.setup();
  158. await openUsersTab();
  159. const buttons = within(userRow('bob')).getAllByRole('button');
  160. await user.click(buttons[buttons.length - 1]);
  161. await user.click(await screen.findByRole('button', { name: /delete user and their items/i }));
  162. await waitFor(() => expect(writes()).toHaveLength(1));
  163. expect(writes()[0]).toMatchObject({ method: 'DELETE', path: '/api/v1/users/3', search: '?delete_items=true' });
  164. });
  165. it('delete user with items: "keep items" choice sends delete_items=false', async () => {
  166. const user = userEvent.setup();
  167. await openUsersTab();
  168. const buttons = within(userRow('alice')).getAllByRole('button');
  169. await user.click(buttons[buttons.length - 1]);
  170. await user.click(await screen.findByRole('button', { name: /keep items/i }));
  171. await waitFor(() => expect(writes()).toHaveLength(1));
  172. expect(writes()[0]).toMatchObject({ method: 'DELETE', path: '/api/v1/users/2', search: '?delete_items=false' });
  173. });
  174. it('cancelling the delete-user dialog sends nothing', async () => {
  175. const user = userEvent.setup();
  176. await openUsersTab();
  177. const buttons = within(userRow('bob')).getAllByRole('button');
  178. await user.click(buttons[buttons.length - 1]);
  179. await screen.findByRole('button', { name: /delete user and their items/i });
  180. await user.click(screen.getByRole('button', { name: /^cancel$/i }));
  181. await waitFor(() =>
  182. expect(screen.queryByRole('button', { name: /delete user and their items/i })).not.toBeInTheDocument(),
  183. );
  184. expect(writes()).toHaveLength(0);
  185. });
  186. it('the signed-in user has no delete button on their own row', async () => {
  187. await openUsersTab();
  188. // Only the edit button
  189. expect(within(userRow('admin')).getAllByRole('button')).toHaveLength(1);
  190. });
  191. it('delete group asks first, then DELETEs that group; cancel sends nothing', async () => {
  192. const user = userEvent.setup();
  193. await openUsersTab();
  194. // System groups: edit only, no delete button
  195. expect(within(groupRow('Administrators')).getAllByRole('button')).toHaveLength(1);
  196. const deleteNightShift = () => {
  197. const buttons = within(groupRow('Night shift')).getAllByRole('button');
  198. expect(buttons).toHaveLength(2);
  199. return buttons[1];
  200. };
  201. await user.click(deleteNightShift());
  202. await user.click(screen.getByRole('button', { name: /^cancel$/i }));
  203. expect(writes()).toHaveLength(0);
  204. await user.click(deleteNightShift());
  205. await user.click(screen.getByRole('button', { name: /^delete group$/i }));
  206. await waitFor(() => expect(writes()).toHaveLength(1));
  207. expect(writes()[0]).toMatchObject({ method: 'DELETE', path: '/api/v1/groups/6' });
  208. });
  209. it('disable authentication asks first; cancel sends nothing, confirm POSTs /auth/disable', async () => {
  210. const user = userEvent.setup();
  211. await openUsersTab();
  212. await user.click(await screen.findByRole('button', { name: /^disable$/i }));
  213. await user.click(screen.getByRole('button', { name: /^cancel$/i }));
  214. expect(writes()).toHaveLength(0);
  215. await user.click(screen.getByRole('button', { name: /^disable$/i }));
  216. await user.click(screen.getByRole('button', { name: /^disable authentication$/i }));
  217. await waitFor(() => expect(writes()).toHaveLength(1));
  218. expect(writes()[0]).toMatchObject({ method: 'POST', path: '/api/v1/auth/disable' });
  219. });
  220. it('reset password (advanced auth) POSTs {user_id} of the user being edited', async () => {
  221. server.use(
  222. http.get('*/api/v1/auth/advanced-auth/status', () =>
  223. HttpResponse.json({ advanced_auth_enabled: true, smtp_configured: true, local_login_enabled: true, autologin_provider_id: null }),
  224. ),
  225. http.post('*/api/v1/auth/reset-password', async ({ request }) => {
  226. await capture(request);
  227. return HttpResponse.json({ message: 'sent' });
  228. }),
  229. );
  230. const user = userEvent.setup();
  231. await openUsersTab();
  232. const [editBtn] = within(userRow('alice')).getAllByRole('button');
  233. await user.click(editBtn);
  234. await user.click(await screen.findByRole('button', { name: /reset password/i }));
  235. await waitFor(() => expect(writes()).toHaveLength(1));
  236. expect(writes()[0]).toMatchObject({ method: 'POST', path: '/api/v1/auth/reset-password', body: { user_id: 2 } });
  237. });
  238. it('without create/delete permissions there is no add-user, delete-user, delete-group or disable-auth button', async () => {
  239. meIsAdmin = false;
  240. mePermissions = ['settings:read', 'users:read', 'users:update', 'groups:read'];
  241. await openUsersTab();
  242. expect(screen.queryByRole('button', { name: /add user/i })).not.toBeInTheDocument();
  243. // Edit only
  244. expect(within(userRow('bob')).getAllByRole('button')).toHaveLength(1);
  245. expect(within(groupRow('Night shift')).queryAllByRole('button')).toHaveLength(0);
  246. expect(screen.queryByRole('button', { name: /^disable$/i })).not.toBeInTheDocument();
  247. });
  248. });