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