+export const cancelLinking = () =>
+ async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+ let user: UserResource | undefined;
+ try {
+ dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
+ // When linking is cancelled switch to the originating user (i.e. the user saved in session data)
+ const linkAccountData = services.linkAccountService.getAccountToLink();
+ if (linkAccountData) {
+ dispatch(saveApiToken(linkAccountData.token));
+ user = await services.userService.get(linkAccountData.userUuid);
+ dispatch(switchUser(user, linkAccountData.token));
+ }
+ }
+ finally {
+ services.linkAccountService.removeAccountToLink();
+ dispatch(linkAccountPanelActions.LINK_INIT({targetUser:user}));
+ dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
+ }
+ };
+
+export const linkAccount = () =>
+ async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+ const linkState = getState().linkAccountPanel;
+ if (linkState.userToLink && linkState.userToLinkToken && linkState.targetUser && linkState.targetUserToken) {
+
+ // First create a project owned by the target user
+ const projectName = `Migrated from ${linkState.userToLink.email} (${linkState.userToLink.uuid})`;
+ let newGroup: GroupResource;
+ try {
+ newGroup = await services.projectService.create({
+ name: projectName,
+ ensure_unique_name: true
+ });
+ }
+ catch (e) {
+ dispatch(linkFailed());
+ throw e;
+ }
+
+ try {
+ // The merge api links the user sending the request into the user
+ // specified in the request, so switch users for this api call
+ dispatch(saveApiToken(linkState.userToLinkToken));
+ await services.linkAccountService.linkAccounts(linkState.targetUserToken, newGroup.uuid);
+ dispatch(switchUser(linkState.targetUser, linkState.targetUserToken));
+ services.linkAccountService.removeAccountToLink();
+ services.linkAccountService.saveLinkOpStatus(LinkAccountStatus.SUCCESS);
+ location.reload();
+ }
+ catch(e) {
+ // If the link operation fails, delete the previously made project
+ try {
+ dispatch(saveApiToken(linkState.targetUserToken));
+ await services.projectService.delete(newGroup.uuid);
+ }
+ finally {
+ dispatch(linkFailed());
+ }
+ throw e;
+ }
+ }