5fb6160c423760560273aa28774162cd968b510d
[arvados-workbench2.git] / src / store / link-account-panel / link-account-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 { RootState } from "store/store";
7 import { getUserUuid } from "common/getuser";
8 import { ServiceRepository, createServices, setAuthorizationHeader } from "services/services";
9 import { setBreadcrumbs } from "store/breadcrumbs/breadcrumbs-actions";
10 import { snackbarActions, SnackbarKind } from "store/snackbar/snackbar-actions";
11 import { LinkAccountType, AccountToLink, LinkAccountStatus } from "models/link-account";
12 import { authActions, getConfig } from "store/auth/auth-action";
13 import { unionize, ofType, UnionOf } from 'common/unionize';
14 import { UserResource } from "models/user";
15 import { GroupResource } from "models/group";
16 import { LinkAccountPanelError, OriginatingUser } from "./link-account-panel-reducer";
17 import { login, logout } from "store/auth/auth-action";
18 import { progressIndicatorActions } from "store/progress-indicator/progress-indicator-actions";
19 import { WORKBENCH_LOADING_SCREEN } from 'store/workbench/workbench-actions';
20
21 export const linkAccountPanelActions = unionize({
22     LINK_INIT: ofType<{
23         targetUser: UserResource | undefined
24     }>(),
25     LINK_LOAD: ofType<{
26         originatingUser: OriginatingUser | undefined,
27         targetUser: UserResource | undefined,
28         targetUserToken: string | undefined,
29         userToLink: UserResource | undefined,
30         userToLinkToken: string | undefined
31     }>(),
32     LINK_INVALID: ofType<{
33         originatingUser: OriginatingUser | undefined,
34         targetUser: UserResource | undefined,
35         userToLink: UserResource | undefined,
36         error: LinkAccountPanelError
37     }>(),
38     SET_SELECTED_CLUSTER: ofType<{
39         selectedCluster: string
40     }>(),
41     SET_IS_PROCESSING: ofType<{
42         isProcessing: boolean
43     }>(),
44     HAS_SESSION_DATA: {}
45 });
46
47 export type LinkAccountPanelAction = UnionOf<typeof linkAccountPanelActions>;
48
49 function validateLink(userToLink: UserResource, targetUser: UserResource) {
50     if (userToLink.uuid === targetUser.uuid) {
51         return LinkAccountPanelError.SAME_USER;
52     }
53     else if (userToLink.isAdmin && !targetUser.isAdmin) {
54         return LinkAccountPanelError.NON_ADMIN;
55     }
56     else if (!targetUser.isActive) {
57         return LinkAccountPanelError.INACTIVE;
58     }
59     return LinkAccountPanelError.NONE;
60 }
61
62 const newServices = (dispatch: Dispatch<any>, token: string) => {
63     const config = dispatch<any>(getConfig);
64     const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
65     setAuthorizationHeader(svc, token);
66     return svc;
67 };
68
69 export const checkForLinkStatus = () =>
70     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
71         const status = services.linkAccountService.getLinkOpStatus();
72         if (status !== undefined) {
73             let msg: string;
74             let msgKind: SnackbarKind;
75             if (status.valueOf() === LinkAccountStatus.CANCELLED) {
76                 msg = "Account link cancelled!", msgKind = SnackbarKind.INFO;
77             }
78             else if (status.valueOf() === LinkAccountStatus.FAILED) {
79                 msg = "Account link failed!", msgKind = SnackbarKind.ERROR;
80             }
81             else if (status.valueOf() === LinkAccountStatus.SUCCESS) {
82                 msg = "Account link success!", msgKind = SnackbarKind.SUCCESS;
83             }
84             else {
85                 msg = "Unknown Error!", msgKind = SnackbarKind.ERROR;
86             }
87             dispatch(snackbarActions.OPEN_SNACKBAR({ message: msg, kind: msgKind, hideDuration: 3000 }));
88             services.linkAccountService.removeLinkOpStatus();
89         }
90     };
91
92 export const switchUser = (user: UserResource, token: string) =>
93     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
94         dispatch(authActions.INIT_USER({ user, token }));
95     };
96
97 export const linkFailed = () =>
98     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
99         // If the link fails, switch to the user account that originated the link operation
100         const linkState = getState().linkAccountPanel;
101         if (linkState.userToLink && linkState.userToLinkToken && linkState.targetUser && linkState.targetUserToken) {
102             if (linkState.originatingUser === OriginatingUser.TARGET_USER) {
103                 dispatch(switchUser(linkState.targetUser, linkState.targetUserToken));
104             }
105             else if ((linkState.originatingUser === OriginatingUser.USER_TO_LINK)) {
106                 dispatch(switchUser(linkState.userToLink, linkState.userToLinkToken));
107             }
108         }
109         services.linkAccountService.removeAccountToLink();
110         services.linkAccountService.saveLinkOpStatus(LinkAccountStatus.FAILED);
111         location.reload();
112     };
113
114 export const loadLinkAccountPanel = () =>
115     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
116         try {
117             // If there are remote hosts, set the initial selected cluster by getting the first cluster that isn't the local cluster
118             if (getState().linkAccountPanel.selectedCluster === undefined) {
119                 const localCluster = getState().auth.localCluster;
120                 let selectedCluster = localCluster;
121                 for (const key in getState().auth.remoteHosts) {
122                     if (key !== localCluster) {
123                         selectedCluster = key;
124                         break;
125                     }
126                 }
127                 dispatch(linkAccountPanelActions.SET_SELECTED_CLUSTER({ selectedCluster }));
128             }
129
130             // First check if an account link operation has completed
131             dispatch(checkForLinkStatus());
132
133             // Continue loading the link account panel
134             dispatch(setBreadcrumbs([{ label: 'Link account' }]));
135             const curUser = getState().auth.user;
136             const curToken = getState().auth.apiToken;
137             if (curUser && curToken) {
138
139                 // If there is link account session data, then the user has logged in a second time
140                 const linkAccountData = services.linkAccountService.getAccountToLink();
141                 if (linkAccountData) {
142
143                     dispatch(linkAccountPanelActions.SET_IS_PROCESSING({ isProcessing: true }));
144                     const curUserResource = await services.userService.get(curUser.uuid);
145
146                     // Use the token of the user we are getting data for. This avoids any admin/non-admin permissions
147                     // issues since a user will always be able to query the api server for their own user data.
148                     const svc = newServices(dispatch, linkAccountData.token);
149                     const savedUserResource = await svc.userService.get(linkAccountData.userUuid);
150
151                     let params: any;
152                     if (linkAccountData.type === LinkAccountType.ACCESS_OTHER_ACCOUNT || linkAccountData.type === LinkAccountType.ACCESS_OTHER_REMOTE_ACCOUNT) {
153                         params = {
154                             originatingUser: OriginatingUser.USER_TO_LINK,
155                             targetUser: curUserResource,
156                             targetUserToken: curToken,
157                             userToLink: savedUserResource,
158                             userToLinkToken: linkAccountData.token
159                         };
160                     }
161                     else if (linkAccountData.type === LinkAccountType.ADD_OTHER_LOGIN || linkAccountData.type === LinkAccountType.ADD_LOCAL_TO_REMOTE) {
162                         params = {
163                             originatingUser: OriginatingUser.TARGET_USER,
164                             targetUser: savedUserResource,
165                             targetUserToken: linkAccountData.token,
166                             userToLink: curUserResource,
167                             userToLinkToken: curToken
168                         };
169                     }
170                     else {
171                         throw new Error("Unknown link account type");
172                     }
173
174                     dispatch(switchUser(params.targetUser, params.targetUserToken));
175                     const error = validateLink(params.userToLink, params.targetUser);
176                     if (error === LinkAccountPanelError.NONE) {
177                         dispatch(linkAccountPanelActions.LINK_LOAD(params));
178                     }
179                     else {
180                         dispatch(linkAccountPanelActions.LINK_INVALID({
181                             originatingUser: params.originatingUser,
182                             targetUser: params.targetUser,
183                             userToLink: params.userToLink,
184                             error
185                         }));
186                         return;
187                     }
188                 }
189                 else {
190                     // If there is no link account session data, set the state to invoke the initial UI
191                     const curUserResource = await services.userService.get(curUser.uuid);
192                     dispatch(linkAccountPanelActions.LINK_INIT({ targetUser: curUserResource }));
193                     return;
194                 }
195             }
196         }
197         catch (e) {
198             dispatch(linkFailed());
199         }
200         finally {
201             dispatch(linkAccountPanelActions.SET_IS_PROCESSING({ isProcessing: false }));
202         }
203     };
204
205 export const startLinking = (t: LinkAccountType) =>
206     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
207         const userUuid = getUserUuid(getState());
208         if (!userUuid) { return; }
209         const accountToLink = { type: t, userUuid, token: services.authService.getApiToken() } as AccountToLink;
210         services.linkAccountService.saveAccountToLink(accountToLink);
211
212         const auth = getState().auth;
213         const isLocalUser = auth.user!.uuid.substring(0, 5) === auth.localCluster;
214         let homeCluster = auth.localCluster;
215         if (isLocalUser && t === LinkAccountType.ACCESS_OTHER_REMOTE_ACCOUNT) {
216             homeCluster = getState().linkAccountPanel.selectedCluster!;
217         }
218
219         dispatch(logout());
220         dispatch(login(auth.localCluster, homeCluster, auth.loginCluster, auth.remoteHosts));
221     };
222
223 export const getAccountLinkData = () =>
224     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
225         return services.linkAccountService.getAccountToLink();
226     };
227
228 export const cancelLinking = (reload: boolean = false) =>
229     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
230         let user: UserResource | undefined;
231         try {
232             // When linking is cancelled switch to the originating user (i.e. the user saved in session data)
233             dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
234             const linkAccountData = services.linkAccountService.getAccountToLink();
235             if (linkAccountData) {
236                 services.linkAccountService.removeAccountToLink();
237                 const svc = newServices(dispatch, linkAccountData.token);
238                 user = await svc.userService.get(linkAccountData.userUuid);
239                 dispatch(switchUser(user, linkAccountData.token));
240                 services.linkAccountService.saveLinkOpStatus(LinkAccountStatus.CANCELLED);
241             }
242         }
243         finally {
244             if (reload) {
245                 location.reload();
246             }
247             else {
248                 dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
249             }
250         }
251     };
252
253 export const linkAccount = () =>
254     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
255         const linkState = getState().linkAccountPanel;
256         if (linkState.userToLink && linkState.userToLinkToken && linkState.targetUser && linkState.targetUserToken) {
257
258             // First create a project owned by the target user
259             const projectName = `Migrated from ${linkState.userToLink.email} (${linkState.userToLink.uuid})`;
260             let newGroup: GroupResource;
261             try {
262                 newGroup = await services.projectService.create({
263                     name: projectName,
264                     ensure_unique_name: true
265                 });
266             }
267             catch (e) {
268                 dispatch(linkFailed());
269                 throw e;
270             }
271
272             try {
273                 // The merge api links the user sending the request into the user
274                 // specified in the request, so change the authorization header accordingly
275                 const svc = newServices(dispatch, linkState.userToLinkToken);
276                 await svc.linkAccountService.linkAccounts(linkState.targetUserToken, newGroup.uuid);
277                 dispatch(switchUser(linkState.targetUser, linkState.targetUserToken));
278                 services.linkAccountService.removeAccountToLink();
279                 services.linkAccountService.saveLinkOpStatus(LinkAccountStatus.SUCCESS);
280                 location.reload();
281             }
282             catch (e) {
283                 // If the link operation fails, delete the previously made project
284                 try {
285                     const svc = newServices(dispatch, linkState.targetUserToken);
286                     await svc.projectService.delete(newGroup.uuid);
287                 }
288                 finally {
289                     dispatch(linkFailed());
290                 }
291                 throw e;
292             }
293         }
294     };