27558618d8017b17465e06ea388f03240a77b249
[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<{ extraApiToken: string, extraApiTokenExpiration?: Date }>(),
26     INIT_USER: ofType<{ user: User, token: string, tokenExpiration?: Date }>(),
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) => async (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     try {
90         const user = await svc.authService.getUserDetails();
91         const client = await svc.apiClientAuthorizationService.get('current');
92         const tokenExpiration = client.expiresAt ? new Date(client.expiresAt) : undefined;
93         dispatch(authActions.INIT_USER({ user, token, tokenExpiration }));
94     } catch (e) {
95         dispatch(authActions.LOGOUT({ deleteLinkData: false }));
96     }
97 };
98
99 export const getNewExtraToken = (reuseStored: boolean = false) =>
100     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
101         const extraToken = getState().auth.extraApiToken;
102         if (reuseStored && extraToken !== undefined) {
103             const config = dispatch<any>(getConfig);
104             const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
105             setAuthorizationHeader(svc, extraToken);
106             try {
107                 // Check the extra token's validity before using it. Refresh its
108                 // expiration date just in case it changed.
109                 const client = await svc.apiClientAuthorizationService.get('current');
110                 dispatch(authActions.SET_EXTRA_TOKEN({
111                     extraApiToken: extraToken,
112                     extraApiTokenExpiration: client.expiresAt ? new Date(client.expiresAt): undefined,
113                 }));
114                 return extraToken;
115             } catch (e) { }
116         }
117         const user = getState().auth.user;
118         const loginCluster = getState().auth.config.clusterConfig.Login.LoginCluster;
119         if (user === undefined) { return; }
120         if (loginCluster !== "" && getState().auth.homeCluster !== loginCluster) { return; }
121         try {
122             // Do not show errors on the create call, cluster security configuration may not
123             // allow token creation and there's no way to know that from workbench2 side in advance.
124             const client = await services.apiClientAuthorizationService.create(undefined, false);
125             const newExtraToken = getTokenV2(client);
126             dispatch(authActions.SET_EXTRA_TOKEN({
127                 extraApiToken: newExtraToken,
128                 extraApiTokenExpiration: client.expiresAt ? new Date(client.expiresAt): undefined,
129             }));
130             return newExtraToken;
131         } catch {
132             console.warn("Cannot create new tokens with the current token, probably because of cluster's security settings.");
133             return;
134         }
135     };
136
137 export const login = (uuidPrefix: string, homeCluster: string, loginCluster: string,
138     remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
139         services.authService.login(uuidPrefix, homeCluster, loginCluster, remoteHosts);
140         dispatch(authActions.LOGIN());
141     };
142
143 export const logout = (deleteLinkData: boolean = false) =>
144     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) =>
145         dispatch(authActions.LOGOUT({ deleteLinkData }));
146
147 export type AuthAction = UnionOf<typeof authActions>;