Merge branch '16417-installer-loki'
[arvados.git] / services / workbench2 / src / store / groups-panel / groups-panel-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from 'redux';
6 import { reset, startSubmit, stopSubmit, FormErrors, initialize } from 'redux-form';
7 import { bindDataExplorerActions } from "store/data-explorer/data-explorer-action";
8 import { dialogActions } from 'store/dialog/dialog-actions';
9 import { RootState } from 'store/store';
10 import { ServiceRepository } from 'services/services';
11 import { getResource } from 'store/resources/resources';
12 import { GroupResource, GroupClass } from 'models/group';
13 import { getCommonResourceServiceError, CommonResourceServiceError } from 'services/common-service/common-resource-service';
14 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
15 import { PermissionLevel } from 'models/permission';
16 import { PermissionService } from 'services/permission-service/permission-service';
17 import { FilterBuilder } from 'services/api/filter-builder';
18 import { ProjectUpdateFormDialogData, PROJECT_UPDATE_FORM_NAME } from 'store/projects/project-update-actions';
19 import { PROJECT_CREATE_FORM_NAME } from 'store/projects/project-create-actions';
20 import { selectedToArray, isGroupResource } from 'components/multiselect-toolbar/MultiselectToolbar';
21
22 export const GROUPS_PANEL_ID = "groupsPanel";
23
24 export const GROUP_ATTRIBUTES_DIALOG = 'groupAttributesDialog';
25 export const GROUP_REMOVE_DIALOG = 'groupRemoveDialog';
26
27 export const GroupsPanelActions = bindDataExplorerActions(GROUPS_PANEL_ID);
28
29 export const loadGroupsPanel = () => (dispatch: Dispatch) => {
30     dispatch(GroupsPanelActions.RESET_EXPLORER_SEARCH_VALUE());
31     dispatch(GroupsPanelActions.REQUEST_ITEMS());
32 };
33
34 export const openCreateGroupDialog = () =>
35     (dispatch: Dispatch, getState: () => RootState) => {
36         dispatch(initialize(PROJECT_CREATE_FORM_NAME, {}));
37         dispatch(dialogActions.OPEN_DIALOG({
38             id: PROJECT_CREATE_FORM_NAME,
39             data: {
40                 sourcePanel: GroupClass.ROLE,
41             }
42         }));
43     };
44
45 export const openGroupAttributes = (uuid: string) =>
46     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
47         const { resources } = getState();
48         const data = getResource<GroupResource>(uuid)(resources);
49         dispatch(dialogActions.OPEN_DIALOG({ id: GROUP_ATTRIBUTES_DIALOG, data }));
50     };
51
52 export const removeGroup = (uuid: string) =>
53     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
54         const { multiselect, resources } = getState();
55         const groupsToRemove = selectedToArray(multiselect.checkedList).filter(uuid => isGroupResource(uuid, resources));
56         if (!groupsToRemove.length) groupsToRemove.push(uuid);
57         for (const group of groupsToRemove) {
58             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...', kind: SnackbarKind.INFO }));
59             await services.groupsService.delete(group);
60             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removed.', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
61         }
62         dispatch<any>(loadGroupsPanel());
63     };
64
65 export const openRemoveGroupDialog = (uuid: string, numOfGroups = 1) =>
66     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
67         const titleText = numOfGroups > 1 ? 'Remove groups' : 'Remove group';
68         const confirmationText = numOfGroups > 1 ? `Are you sure you want to remove these ${numOfGroups} groups?` : 'Are you sure you want to remove this group?';
69         dispatch(dialogActions.OPEN_DIALOG({
70             id: GROUP_REMOVE_DIALOG,
71             data: {
72                 title: titleText,
73                 text: confirmationText,
74                 confirmButtonLabel: 'Remove',
75                 uuid
76             }
77         }));
78     };
79
80 // Group edit dialog uses project update dialog with sourcePanel set to reload the appropriate parts
81 export const openGroupUpdateDialog = (resource: ProjectUpdateFormDialogData) =>
82     (dispatch: Dispatch, getState: () => RootState) => {
83         dispatch(initialize(PROJECT_UPDATE_FORM_NAME, resource));
84         dispatch(dialogActions.OPEN_DIALOG({
85             id: PROJECT_UPDATE_FORM_NAME,
86             data: {
87                 sourcePanel: GroupClass.ROLE,
88             }
89         }));
90     };
91
92 export const updateGroup = (project: ProjectUpdateFormDialogData) =>
93     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
94         const uuid = project.uuid || '';
95         dispatch(startSubmit(PROJECT_UPDATE_FORM_NAME));
96         try {
97             const updatedGroup = await services.groupsService.update(uuid, { name: project.name, description: project.description });
98             dispatch(GroupsPanelActions.REQUEST_ITEMS());
99             dispatch(reset(PROJECT_UPDATE_FORM_NAME));
100             dispatch(dialogActions.CLOSE_DIALOG({ id: PROJECT_UPDATE_FORM_NAME }));
101             return updatedGroup;
102         } catch (e) {
103             dispatch(stopSubmit(PROJECT_UPDATE_FORM_NAME));
104             const error = getCommonResourceServiceError(e);
105             if (error === CommonResourceServiceError.UNIQUE_NAME_VIOLATION) {
106                 dispatch(stopSubmit(PROJECT_UPDATE_FORM_NAME, { name: 'Group with the same name already exists.' } as FormErrors));
107             }
108             return ;
109         }
110     };
111
112 export const createGroup = ({ name, users = [], description }: ProjectUpdateFormDialogData) =>
113     async (dispatch: Dispatch, _: {}, { groupsService, permissionService }: ServiceRepository) => {
114         dispatch(startSubmit(PROJECT_CREATE_FORM_NAME));
115         try {
116             const newGroup = await groupsService.create({ name, description, groupClass: GroupClass.ROLE });
117             for (const user of users) {
118                 await addGroupMember({
119                     user,
120                     group: newGroup,
121                     dispatch,
122                     permissionService,
123                 });
124             }
125             dispatch(dialogActions.CLOSE_DIALOG({ id: PROJECT_CREATE_FORM_NAME }));
126             dispatch(reset(PROJECT_CREATE_FORM_NAME));
127             dispatch<any>(loadGroupsPanel());
128             dispatch(snackbarActions.OPEN_SNACKBAR({
129                 message: `${newGroup.name} group has been created`,
130                 kind: SnackbarKind.SUCCESS
131             }));
132             return newGroup;
133         } catch (e) {
134             const error = getCommonResourceServiceError(e);
135             if (error === CommonResourceServiceError.UNIQUE_NAME_VIOLATION) {
136                 dispatch(stopSubmit(PROJECT_CREATE_FORM_NAME, { name: 'Group with the same name already exists.' } as FormErrors));
137             }
138             return;
139         }
140     };
141
142 interface AddGroupMemberArgs {
143     user: { uuid: string, name: string };
144     group: { uuid: string, name: string };
145     dispatch: Dispatch;
146     permissionService: PermissionService;
147 }
148
149 /**
150  * Group membership is determined by whether the group has can_read permission on an object.
151  * If a group G can_read an object A, then we say A is a member of G.
152  *
153  * [Permission model docs](https://doc.arvados.org/api/permission-model.html)
154  */
155 export const addGroupMember = async ({ user, group, ...args }: AddGroupMemberArgs) => {
156     await createPermission({
157         head: { ...group },
158         tail: { ...user },
159         permissionLevel: PermissionLevel.CAN_READ,
160         ...args,
161     });
162 };
163
164 interface CreatePermissionLinkArgs {
165     head: { uuid: string, name: string };
166     tail: { uuid: string, name: string };
167     permissionLevel: PermissionLevel;
168     dispatch: Dispatch;
169     permissionService: PermissionService;
170 }
171
172 const createPermission = async ({ head, tail, permissionLevel, dispatch, permissionService }: CreatePermissionLinkArgs) => {
173     try {
174         await permissionService.create({
175             tailUuid: tail.uuid,
176             headUuid: head.uuid,
177             name: permissionLevel,
178         });
179     } catch (e) {
180         dispatch(snackbarActions.OPEN_SNACKBAR({
181             message: `Could not add ${tail.name} -> ${head.name} relation`,
182             kind: SnackbarKind.ERROR,
183         }));
184     }
185 };
186
187 interface DeleteGroupMemberArgs {
188     link: { uuid: string };
189     dispatch: Dispatch;
190     permissionService: PermissionService;
191 }
192
193 export const deleteGroupMember = async ({ link, ...args }: DeleteGroupMemberArgs) => {
194     await deletePermission({
195         uuid: link.uuid,
196         ...args,
197     });
198 };
199
200 interface DeletePermissionLinkArgs {
201     uuid: string;
202     dispatch: Dispatch;
203     permissionService: PermissionService;
204 }
205
206 export const deletePermission = async ({ uuid, dispatch, permissionService }: DeletePermissionLinkArgs) => {
207     try {
208         const permissionsResponse = await permissionService.list({
209             filters: new FilterBuilder()
210                 .addEqual('uuid', uuid)
211                 .getFilters()
212         });
213         const [permission] = permissionsResponse.items;
214         if (permission) {
215             await permissionService.delete(permission.uuid);
216         } else {
217             throw new Error('Permission not found');
218         }
219     } catch (e) {
220         dispatch(snackbarActions.OPEN_SNACKBAR({
221             message: `Could not delete ${uuid} permission`,
222             kind: SnackbarKind.ERROR,
223         }));
224     }
225 };