16848: Avoids showing API errors when the extra token creation fails.
[arvados-workbench2.git] / src / store / auth / auth-action.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { ofType, unionize, UnionOf } from '~/common/unionize';
6 import { Dispatch } from "redux";
7 import { RootState } from "../store";
8 import { ServiceRepository } from "~/services/services";
9 import { SshKeyResource } from '~/models/ssh-key';
10 import { User } from "~/models/user";
11 import { Session } from "~/models/session";
12 import { Config } from '~/common/config';
13 import { matchTokenRoute, matchFedTokenRoute } from '~/routes/routes';
14 import { createServices, setAuthorizationHeader } from "~/services/services";
15 import { cancelLinking } from '~/store/link-account-panel/link-account-panel-actions';
16 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
17 import { WORKBENCH_LOADING_SCREEN } from '~/store/workbench/workbench-actions';
18 import { addRemoteConfig } from './auth-action-session';
19 import { getTokenV2 } from '~/models/api-client-authorization';
20
21 export const authActions = unionize({
22     LOGIN: {},
23     LOGOUT: ofType<{ deleteLinkData: boolean }>(),
24     SET_CONFIG: ofType<{ config: Config }>(),
25     SET_EXTRA_TOKEN: ofType<{ extraToken: string }>(),
26     INIT_USER: ofType<{ user: User, token: string }>(),
27     USER_DETAILS_REQUEST: {},
28     USER_DETAILS_SUCCESS: ofType<User>(),
29     SET_SSH_KEYS: ofType<SshKeyResource[]>(),
30     ADD_SSH_KEY: ofType<SshKeyResource>(),
31     REMOVE_SSH_KEY: ofType<string>(),
32     SET_HOME_CLUSTER: ofType<string>(),
33     SET_SESSIONS: ofType<Session[]>(),
34     ADD_SESSION: ofType<Session>(),
35     REMOVE_SESSION: ofType<string>(),
36     UPDATE_SESSION: ofType<Session>(),
37     REMOTE_CLUSTER_CONFIG: ofType<{ config: Config }>(),
38 });
39
40 export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
41     // Cancel any link account ops in progress unless the user has
42     // just logged in or there has been a successful link operation
43     const data = services.linkAccountService.getLinkOpStatus();
44     if (!matchTokenRoute(location.pathname) &&
45         (!matchFedTokenRoute(location.pathname)) && data === undefined) {
46         dispatch<any>(cancelLinking()).then(() => {
47             dispatch<any>(init(config));
48         });
49     } else {
50         dispatch<any>(init(config));
51     }
52 };
53
54 const init = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
55     const remoteHosts = () => getState().auth.remoteHosts;
56     const token = services.authService.getApiToken();
57     let homeCluster = services.authService.getHomeCluster();
58     if (homeCluster && !config.remoteHosts[homeCluster]) {
59         homeCluster = undefined;
60     }
61     dispatch(authActions.SET_CONFIG({ config }));
62     Object.keys(remoteHosts()).forEach((remoteUuid: string) => {
63         const remoteHost = remoteHosts()[remoteUuid];
64         if (remoteUuid !== config.uuidPrefix) {
65             dispatch<any>(addRemoteConfig(remoteHost));
66         }
67     });
68     dispatch(authActions.SET_HOME_CLUSTER(config.loginCluster || homeCluster || config.uuidPrefix));
69
70     if (token && token !== "undefined") {
71         dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
72         dispatch<any>(saveApiToken(token)).then(() => {
73             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
74         }).catch(() => {
75             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
76         });
77     }
78 };
79
80 export const getConfig = (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Config => {
81     const state = getState().auth;
82     return state.remoteHostsConfig[state.localCluster];
83 };
84
85 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
86     const config = dispatch<any>(getConfig);
87     const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
88     setAuthorizationHeader(svc, token);
89     return svc.authService.getUserDetails().then((user: User) => {
90         dispatch(authActions.INIT_USER({ user, token }));
91         // Upon user init, request an extra token that won't be expired on logout
92         // for other uses like the "get token" dialog, or S3 URL building.
93         dispatch<any>(getNewExtraToken());
94     }).catch(() => {
95         dispatch(authActions.LOGOUT({ deleteLinkData: false }));
96     });
97 };
98
99 export const getNewExtraToken = () =>
100     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
101         const user = getState().auth.user;
102         if (user === undefined) { return; }
103         try {
104             // Do not show errors on the create call, cluster security configuration may not
105             // allow token creation and there's no way to know that from workbench2 side in advance.
106             const client = await services.apiClientAuthorizationService.create(undefined, false);
107             const newExtraToken = getTokenV2(client);
108             dispatch(authActions.SET_EXTRA_TOKEN({ extraToken: newExtraToken }));
109             return newExtraToken;
110         } catch {
111             console.warn("Cannot create new tokens with the current token, probably because of cluster's security settings.");
112             return;
113         }
114     };
115
116 export const login = (uuidPrefix: string, homeCluster: string, loginCluster: string,
117     remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
118         services.authService.login(uuidPrefix, homeCluster, loginCluster, remoteHosts);
119         dispatch(authActions.LOGIN());
120     };
121
122 export const logout = (deleteLinkData: boolean = false) =>
123     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) =>
124         dispatch(authActions.LOGOUT({ deleteLinkData }));
125
126 export type AuthAction = UnionOf<typeof authActions>;