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