diff --git a/docs/docs/assets/images/settings/admin_edit_group.png b/docs/docs/assets/images/settings/admin_edit_group.png new file mode 100644 index 0000000000..f948845527 Binary files /dev/null and b/docs/docs/assets/images/settings/admin_edit_group.png differ diff --git a/docs/docs/assets/images/settings/admin_edit_user.png b/docs/docs/assets/images/settings/admin_edit_user.png new file mode 100644 index 0000000000..c075e3bacd Binary files /dev/null and b/docs/docs/assets/images/settings/admin_edit_user.png differ diff --git a/docs/docs/assets/images/settings/admin_group_roles.png b/docs/docs/assets/images/settings/admin_group_roles.png new file mode 100644 index 0000000000..3fc86fa30a Binary files /dev/null and b/docs/docs/assets/images/settings/admin_group_roles.png differ diff --git a/docs/docs/assets/images/settings/admin_group_users.png b/docs/docs/assets/images/settings/admin_group_users.png new file mode 100644 index 0000000000..abc233bb33 Binary files /dev/null and b/docs/docs/assets/images/settings/admin_group_users.png differ diff --git a/docs/docs/assets/images/settings/admin_groups_table.png b/docs/docs/assets/images/settings/admin_groups_table.png new file mode 100644 index 0000000000..4c14b845ad Binary files /dev/null and b/docs/docs/assets/images/settings/admin_groups_table.png differ diff --git a/docs/docs/assets/images/settings/admin_user_groups.png b/docs/docs/assets/images/settings/admin_user_groups.png new file mode 100644 index 0000000000..e5a667cfc3 Binary files /dev/null and b/docs/docs/assets/images/settings/admin_user_groups.png differ diff --git a/docs/docs/assets/images/settings/admin_users_table.png b/docs/docs/assets/images/settings/admin_users_table.png new file mode 100644 index 0000000000..7f5101a640 Binary files /dev/null and b/docs/docs/assets/images/settings/admin_users_table.png differ diff --git a/docs/docs/settings/admin.md b/docs/docs/settings/admin.md index 3237172951..a7e56f1b45 100644 --- a/docs/docs/settings/admin.md +++ b/docs/docs/settings/admin.md @@ -26,7 +26,7 @@ InvenTree provides multiple administration interfaces with different safety leve The Admin Center is the main interface for managing InvenTree. It provides a user-friendly interface for managing all aspects of the system, including: -- Users / Groups +- [Users / Groups](./permissions.md#managing-users-and-groups) - Data import / export - Customisation (e.g. project codes, custom states, parameters and units) - Operational controls (e.g. background tasks, errors, currencies, identity federation controls) diff --git a/docs/docs/settings/permissions.md b/docs/docs/settings/permissions.md index 291f9bc097..bbb159d0d5 100644 --- a/docs/docs/settings/permissions.md +++ b/docs/docs/settings/permissions.md @@ -53,6 +53,70 @@ It is strongly recommended to register any users with staff / superuser flags wi Practicing account tiering is strongly recommended. +## Managing Users and Groups + +Users and groups are managed from the *Users / Access* panel of the [Admin Center](./admin.md#admin-center). + +!!! info "Required Permissions" + Creating and editing users and groups requires the *staff* flag **and** the relevant permissions for the *Admin* role. Users without these permissions can view the users and groups, but cannot make any changes. + +### Users + +The *Users* table lists all user accounts, along with the number of groups each user belongs to and their *Administrator*, *Superuser* and *Active* flags. Use the {{ icon("plus", color="green") }} button to create a new user. + +{{ image("settings/admin_users_table.png", "Users table") }} + +Click on a user to open the *Edit User* drawer. + +#### User Details + +The *User Details* section allows the user's name and account flags to be edited. + +{{ image("settings/admin_edit_user.png", "Edit user details") }} + +!!! tip "Deactivate Users" + Rather than deleting a user account, consider unchecking the *Is Active* flag. This prevents the user from logging in, while retaining the history of their actions. + +#### User Groups + +The *User Groups* section shows which groups the user belongs to. Move groups between the *Available* and *Selected* lists, then press *Save* to update the user's group memberships. + +{{ image("settings/admin_user_groups.png", "Edit user groups") }} + +### Groups + +The *Groups* table lists all user groups. Use the {{ icon("plus", color="green") }} button to create a new group. + +{{ image("settings/admin_groups_table.png", "Groups table") }} + +Click on a group to open the *Edit Group* drawer. + +#### Group Details + +The *Group Details* section allows the name of the group to be changed. + +{{ image("settings/admin_edit_group.png", "Edit group details") }} + +#### Group Roles + +The *Group Roles* section sets the [role permissions](#role-permissions) for every user in the group. Check the required *View*, *Change*, *Add* and *Delete* permissions for each role, then press *Save*. + +{{ image("settings/admin_group_roles.png", "Edit group roles") }} + +#### Group Users + +The *Group Users* section lists the users who belong to the group. From here, users can be quickly added to or removed from the group: + +- **Add a user** - search for the user in the *Add User* field and select them. The user is added to the group immediately. +- **Remove a user** - press the {{ icon("user-minus", color="red") }} button next to the user. + +These changes only affect membership of this group - the user's other group memberships are not changed. + +{{ image("settings/admin_group_users.png", "Edit group users") }} + +!!! info "Permissions" + Adding or removing users from a group edits the *user* account, so it requires *change* permission for users (as well as the *staff* flag). If you do not have this permission, the list of users is displayed in read-only mode. + ## Database Admin Permissions diff --git a/src/frontend/src/tables/settings/GroupTable.tsx b/src/frontend/src/tables/settings/GroupTable.tsx index 34c687b556..a3046aded8 100644 --- a/src/frontend/src/tables/settings/GroupTable.tsx +++ b/src/frontend/src/tables/settings/GroupTable.tsx @@ -1,8 +1,17 @@ import { t } from '@lingui/core/macro'; import { Trans } from '@lingui/react/macro'; -import { Accordion, LoadingOverlay, Stack, Text } from '@mantine/core'; +import { + Accordion, + Group, + LoadingOverlay, + Stack, + Table, + Text +} from '@mantine/core'; +import { showNotification } from '@mantine/notifications'; import { useCallback, useMemo, useState } from 'react'; +import { ActionButton } from '@lib/components/ActionButton'; import { AddItemButton } from '@lib/components/AddItemButton'; import { type RowAction, @@ -19,11 +28,14 @@ import { getDetailUrl } from '@lib/functions/Navigation'; import useTable from '@lib/hooks/UseTable'; import type { ApiFormModalProps } from '@lib/index'; import type { TableColumn, TableState } from '@lib/types/Tables'; -import { IconUsersGroup } from '@tabler/icons-react'; +import { IconUserMinus, IconUsersGroup } from '@tabler/icons-react'; import { useNavigate } from 'react-router-dom'; +import { api } from '../../App'; import { EditApiForm } from '../../components/forms/ApiForm'; +import { StandaloneField } from '../../components/forms/StandaloneField'; import { RoleTable, type RuleSet } from '../../components/items/RoleTable'; import { InvenTreeTable } from '../../components/tables/InvenTreeTable'; +import { showApiErrorMessage } from '../../functions/notifications'; import { useCreateApiFormModal, useDeleteApiFormModal @@ -36,6 +48,176 @@ export interface GroupDetailI { name: string; } +interface GroupMemberI { + pk: number; + username: string; + first_name?: string; + last_name?: string; + email?: string; +} + +/** + * Display (and optionally edit) the users which belong to a group. + * + * Membership changes are made via the existing user detail endpoint + * (PATCH /api/user// with 'group_ids'), so the same permission checks + * apply as when editing a user's groups from the "Edit User" drawer. + */ +function GroupUsers({ + groupId, + users, + onChange +}: Readonly<{ + groupId: number; + users: GroupMemberI[]; + onChange: () => void; +}>) { + const user = useUserState(); + + // Membership is edited via the user endpoint, which requires staff + user change permission + const canEdit: boolean = useMemo( + () => user.isStaff() && user.hasChangePermission(ModelType.user), + [user] + ); + + const [busy, setBusy] = useState(false); + + // Used to reset the "add user" field after a selection is made + const [fieldKey, setFieldKey] = useState(0); + + const sortedUsers = useMemo( + () => + [...(users ?? [])].sort((a, b) => a.username.localeCompare(b.username)), + [users] + ); + + // Fetch the user's current groups, apply the modification, and save + const updateMembership = useCallback( + async (userId: number, add: boolean) => { + if (!canEdit || busy) return; + + setBusy(true); + + try { + const response = await api.get(apiUrl(ApiEndpoints.user_list, userId)); + const current: number[] = (response.data?.groups ?? []).map( + (g: any) => g.pk + ); + + if (add === current.includes(groupId)) { + // Nothing to do (already a member / already removed) + return; + } + + const group_ids = add + ? [...current, groupId] + : current.filter((pk) => pk !== groupId); + + await api.patch(apiUrl(ApiEndpoints.user_list, userId), { + group_ids + }); + + showNotification({ + title: add ? t`User added` : t`User removed`, + message: add ? t`User added to group` : t`User removed from group`, + color: 'green' + }); + } catch (error) { + showApiErrorMessage({ + error: error, + title: t`Error updating group membership` + }); + } finally { + setBusy(false); + onChange(); + } + }, + [canEdit, busy, groupId, onChange] + ); + + const memberIds: number[] = useMemo( + () => sortedUsers.map((u) => u.pk), + [sortedUsers] + ); + + return ( + + + {canEdit && ( + ({ ...value.filters, is_active: true }), + onValueChange: (value: any) => { + if (!value) return; + const pk = Number(value); + setFieldKey((k) => k + 1); + if (!memberIds.includes(pk)) { + updateMembership(pk, true); + } + } + }} + /> + )} + {sortedUsers.length === 0 ? ( + + No users in this group + + ) : ( + + + + + Username + + + Name + + + Email + + {canEdit && } + + + + {sortedUsers.map((member) => ( + + {member.username} + + {[member.first_name, member.last_name] + .filter(Boolean) + .join(' ')} + + {member.email} + {canEdit && ( + + + } + color='red' + tooltip={t`Remove user from group`} + disabled={busy} + onClick={() => updateMembership(member.pk, false)} + /> + + + )} + + ))} + +
+ )} +
+ ); +} + export function GroupDrawer({ id, refreshTable @@ -61,7 +243,9 @@ export function GroupDrawer({ return instance?.roles ?? []; }, [instance]); - if (isFetching) { + // Only block the drawer on the initial load, so that refreshing the group + // (e.g. after a membership change) does not collapse the open panel + if (isFetching && !instance?.pk) { return ; } @@ -117,6 +301,24 @@ export function GroupDrawer({ + + + + + Group Users + + + + { + refreshInstance(); + refreshTable(); + }} + /> + + ); diff --git a/src/frontend/tests/pui_admin.spec.ts b/src/frontend/tests/pui_admin.spec.ts index 38f5852414..5a514b118c 100644 --- a/src/frontend/tests/pui_admin.spec.ts +++ b/src/frontend/tests/pui_admin.spec.ts @@ -106,6 +106,32 @@ test('Admin - Users and Groups', async ({ browser }) => { await page.keyboard.press('Escape'); await page.waitForTimeout(250); + // Manage the group membership from the "Edit Group" drawer + await page.getByRole('cell', { name: groupName, exact: true }).click(); + await page.getByText('Edit Group').first().waitFor(); + await openAccordion(page, 'Group Users'); + + const groupUsers = page.getByRole('region', { name: 'Group Users' }); + const memberRow = groupUsers.getByRole('row', { + name: new RegExp(userName) + }); + await memberRow.waitFor(); + + // Remove the user from the group + await memberRow.getByLabel('action-button-remove-user-from-group').click(); + await page.getByText('User removed from group').first().waitFor(); + await expect(memberRow).toHaveCount(0); + await groupUsers.getByText('No users in this group').waitFor(); + + // Add the user back into the group + await groupUsers.getByLabel('related-field-user').fill(userName); + await page.getByRole('option', { name: new RegExp(userName) }).click(); + await page.getByText('User added to group').first().waitFor(); + await memberRow.waitFor(); + + await page.keyboard.press('Escape'); + await page.waitForTimeout(250); + // Lock and unlock the user via the row actions const userCell = page.getByRole('cell', { name: userName, exact: true }); await clickOnRowMenu(userCell);