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