1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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';
21 export const linkAccountPanelActions = unionize({
23 targetUser: UserResource | undefined
26 originatingUser: OriginatingUser | undefined,
27 targetUser: UserResource | undefined,
28 targetUserToken: string | undefined,
29 userToLink: UserResource | undefined,
30 userToLinkToken: string | undefined
32 LINK_INVALID: ofType<{
33 originatingUser: OriginatingUser | undefined,
34 targetUser: UserResource | undefined,
35 userToLink: UserResource | undefined,
36 error: LinkAccountPanelError
38 SET_SELECTED_CLUSTER: ofType<{
39 selectedCluster: string
41 SET_IS_PROCESSING: ofType<{
47 export type LinkAccountPanelAction = UnionOf<typeof linkAccountPanelActions>;
49 function validateLink(userToLink: UserResource, targetUser: UserResource) {
50 if (userToLink.uuid === targetUser.uuid) {
51 return LinkAccountPanelError.SAME_USER;
53 else if (userToLink.isAdmin && !targetUser.isAdmin) {
54 return LinkAccountPanelError.NON_ADMIN;
56 else if (!targetUser.isActive) {
57 return LinkAccountPanelError.INACTIVE;
59 return LinkAccountPanelError.NONE;
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);
69 export const checkForLinkStatus = () =>
70 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
71 const status = services.linkAccountService.getLinkOpStatus();
72 if (status !== undefined) {
74 let msgKind: SnackbarKind;
75 if (status.valueOf() === LinkAccountStatus.CANCELLED) {
76 msg = "Account link cancelled!", msgKind = SnackbarKind.INFO;
78 else if (status.valueOf() === LinkAccountStatus.FAILED) {
79 msg = "Account link failed!", msgKind = SnackbarKind.ERROR;
81 else if (status.valueOf() === LinkAccountStatus.SUCCESS) {
82 msg = "Account link success!", msgKind = SnackbarKind.SUCCESS;
85 msg = "Unknown Error!", msgKind = SnackbarKind.ERROR;
87 dispatch(snackbarActions.OPEN_SNACKBAR({ message: msg, kind: msgKind, hideDuration: 3000 }));
88 services.linkAccountService.removeLinkOpStatus();
92 export const switchUser = (user: UserResource, token: string) =>
93 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
94 dispatch(authActions.INIT_USER({ user, token }));
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));
105 else if ((linkState.originatingUser === OriginatingUser.USER_TO_LINK)) {
106 dispatch(switchUser(linkState.userToLink, linkState.userToLinkToken));
109 services.linkAccountService.removeAccountToLink();
110 services.linkAccountService.saveLinkOpStatus(LinkAccountStatus.FAILED);
114 export const loadLinkAccountPanel = () =>
115 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
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;
127 dispatch(linkAccountPanelActions.SET_SELECTED_CLUSTER({ selectedCluster }));
130 // First check if an account link operation has completed
131 dispatch(checkForLinkStatus());
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) {
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) {
143 dispatch(linkAccountPanelActions.SET_IS_PROCESSING({ isProcessing: true }));
144 const curUserResource = await services.userService.get(curUser.uuid);
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);
152 if (linkAccountData.type === LinkAccountType.ACCESS_OTHER_ACCOUNT || linkAccountData.type === LinkAccountType.ACCESS_OTHER_REMOTE_ACCOUNT) {
154 originatingUser: OriginatingUser.USER_TO_LINK,
155 targetUser: curUserResource,
156 targetUserToken: curToken,
157 userToLink: savedUserResource,
158 userToLinkToken: linkAccountData.token
161 else if (linkAccountData.type === LinkAccountType.ADD_OTHER_LOGIN || linkAccountData.type === LinkAccountType.ADD_LOCAL_TO_REMOTE) {
163 originatingUser: OriginatingUser.TARGET_USER,
164 targetUser: savedUserResource,
165 targetUserToken: linkAccountData.token,
166 userToLink: curUserResource,
167 userToLinkToken: curToken
171 throw new Error("Unknown link account type");
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));
180 dispatch(linkAccountPanelActions.LINK_INVALID({
181 originatingUser: params.originatingUser,
182 targetUser: params.targetUser,
183 userToLink: params.userToLink,
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 }));
198 dispatch(linkFailed());
201 dispatch(linkAccountPanelActions.SET_IS_PROCESSING({ isProcessing: false }));
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);
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!;
220 dispatch(login(auth.localCluster, homeCluster, auth.loginCluster, auth.remoteHosts));
223 export const getAccountLinkData = () =>
224 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
225 return services.linkAccountService.getAccountToLink();
228 export const cancelLinking = (reload: boolean = false) =>
229 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
230 let user: UserResource | undefined;
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);
248 dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
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) {
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;
262 newGroup = await services.projectService.create({
264 ensure_unique_name: true
268 dispatch(linkFailed());
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);
283 // If the link operation fails, delete the previously made project
285 const svc = newServices(dispatch, linkState.targetUserToken);
286 await svc.projectService.delete(newGroup.uuid);
289 dispatch(linkFailed());