15088: Adds federated account linking
[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                 dispatch(linkAccountPanelActions.LINK_INIT({targetUser: linkState.targetUser}));
91             }
92             else if ((linkState.originatingUser === OriginatingUser.USER_TO_LINK)) {
93                 dispatch(switchUser(linkState.userToLink, linkState.userToLinkToken));
94                 dispatch(linkAccountPanelActions.LINK_INIT({targetUser: linkState.userToLink}));
95             }
96             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Account link failed.', kind: SnackbarKind.ERROR , hideDuration: 3000 }));
97         }
98         services.linkAccountService.removeAccountToLink();
99     };
100
101 export const loadLinkAccountPanel = () =>
102     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
103         if (getState().linkAccountPanel.selectedCluster === undefined) {
104             dispatch(linkAccountPanelActions.SET_SELECTED_CLUSTER({ selectedCluster: getState().auth.localCluster }));
105         }
106
107         // First check if an account link operation has completed
108         dispatch(checkForLinkStatus());
109
110         // Continue loading the link account panel
111         dispatch(setBreadcrumbs([{ label: 'Link account'}]));
112         const curUser = getState().auth.user;
113         const curToken = getState().auth.apiToken;
114         if (curUser && curToken) {
115             const curUserResource = await services.userService.get(curUser.uuid);
116             const linkAccountData = services.linkAccountService.getAccountToLink();
117
118             // If there is link account session data, then the user has logged in a second time
119             if (linkAccountData) {
120
121                 // Use the token of the user we are getting data for. This avoids any admin/non-admin permissions
122                 // issues since a user will always be able to query the api server for their own user data.
123                 dispatch(saveApiToken(linkAccountData.token));
124                 const savedUserResource = await services.userService.get(linkAccountData.userUuid);
125                 dispatch(saveApiToken(curToken));
126
127                 let params: any;
128                 if (linkAccountData.type === LinkAccountType.ACCESS_OTHER_ACCOUNT) {
129                     params = {
130                         originatingUser: OriginatingUser.USER_TO_LINK,
131                         targetUser: curUserResource,
132                         targetUserToken: curToken,
133                         userToLink: savedUserResource,
134                         userToLinkToken: linkAccountData.token
135                     };
136                 }
137                 else if (linkAccountData.type === LinkAccountType.ADD_OTHER_LOGIN) {
138                     params = {
139                         originatingUser: OriginatingUser.TARGET_USER,
140                         targetUser: savedUserResource,
141                         targetUserToken: linkAccountData.token,
142                         userToLink: curUserResource,
143                         userToLinkToken: curToken
144                     };
145                 }
146                 else {
147                     // This should never really happen, but just in case, switch to the user that
148                     // originated the linking operation (i.e. the user saved in session data)
149                     dispatch(switchUser(savedUserResource, linkAccountData.token));
150                     services.linkAccountService.removeAccountToLink();
151                     dispatch(linkAccountPanelActions.LINK_INIT({targetUser:savedUserResource}));
152                 }
153
154                 dispatch(switchUser(params.targetUser, params.targetUserToken));
155                 const error = validateLink(params.userToLink, params.targetUser);
156                 if (error === LinkAccountPanelError.NONE) {
157                     dispatch(linkAccountPanelActions.LINK_LOAD(params));
158                 }
159                 else {
160                     dispatch(linkAccountPanelActions.LINK_INVALID({
161                         originatingUser: params.originatingUser,
162                         targetUser: params.targetUser,
163                         userToLink: params.userToLink,
164                         error}));
165                     return;
166                 }
167             }
168             else {
169                 // If there is no link account session data, set the state to invoke the initial UI
170                 dispatch(linkAccountPanelActions.LINK_INIT({ targetUser: curUserResource }));
171                 return;
172             }
173         }
174     };
175
176 export const startLinking = (t: LinkAccountType) =>
177     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
178         const accountToLink = {type: t, userUuid: services.authService.getUuid(), token: services.authService.getApiToken()} as AccountToLink;
179         services.linkAccountService.saveAccountToLink(accountToLink);
180         const auth = getState().auth;
181         const selectedCluster = getState().linkAccountPanel.selectedCluster;
182         const homeCluster = selectedCluster ? selectedCluster : auth.homeCluster;
183         dispatch(logout());
184         dispatch(login(auth.localCluster, homeCluster, auth.remoteHosts));
185     };
186
187 export const getAccountLinkData = () =>
188     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
189         return services.linkAccountService.getAccountToLink();
190     };
191
192 export const cancelLinking = () =>
193     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
194         let user: UserResource | undefined;
195         try {
196             dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
197             // When linking is cancelled switch to the originating user (i.e. the user saved in session data)
198             const linkAccountData = services.linkAccountService.getAccountToLink();
199             if (linkAccountData) {
200                 dispatch(saveApiToken(linkAccountData.token));
201                 user = await services.userService.get(linkAccountData.userUuid);
202                 dispatch(switchUser(user, linkAccountData.token));
203             }
204         }
205         finally {
206             services.linkAccountService.removeAccountToLink();
207             dispatch(linkAccountPanelActions.LINK_INIT({targetUser:user}));
208             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
209         }
210     };
211
212 export const linkAccount = () =>
213     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
214         const linkState = getState().linkAccountPanel;
215         if (linkState.userToLink && linkState.userToLinkToken && linkState.targetUser && linkState.targetUserToken) {
216
217             // First create a project owned by the target user
218             const projectName = `Migrated from ${linkState.userToLink.email} (${linkState.userToLink.uuid})`;
219             let newGroup: GroupResource;
220             try {
221                 newGroup = await services.projectService.create({
222                     name: projectName,
223                     ensure_unique_name: true
224                 });
225             }
226             catch (e) {
227                 dispatch(linkFailed());
228                 throw e;
229             }
230
231             try {
232                 // The merge api links the user sending the request into the user
233                 // specified in the request, so switch users for this api call
234                 dispatch(saveApiToken(linkState.userToLinkToken));
235                 await services.linkAccountService.linkAccounts(linkState.targetUserToken, newGroup.uuid);
236                 dispatch(switchUser(linkState.targetUser, linkState.targetUserToken));
237                 services.linkAccountService.removeAccountToLink();
238                 services.linkAccountService.saveLinkOpStatus(LinkAccountStatus.SUCCESS);
239                 location.reload();
240             }
241             catch(e) {
242                 // If the link operation fails, delete the previously made project
243                 try {
244                     dispatch(saveApiToken(linkState.targetUserToken));
245                     await services.projectService.delete(newGroup.uuid);
246                 }
247                 finally {
248                     dispatch(linkFailed());
249                 }
250                 throw e;
251             }
252         }
253     };