4f576fe4efcd83df36ef8641f330daddeeb9315e
[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     RESET_EXTRA_TOKEN: {},
27     INIT_USER: ofType<{ user: User, token: string, tokenExpiration?: Date }>(),
28     USER_DETAILS_REQUEST: {},
29     USER_DETAILS_SUCCESS: ofType<User>(),
30     SET_SSH_KEYS: ofType<SshKeyResource[]>(),
31     ADD_SSH_KEY: ofType<SshKeyResource>(),
32     REMOVE_SSH_KEY: ofType<string>(),
33     SET_HOME_CLUSTER: ofType<string>(),
34     SET_SESSIONS: ofType<Session[]>(),
35     ADD_SESSION: ofType<Session>(),
36     REMOVE_SESSION: ofType<string>(),
37     UPDATE_SESSION: ofType<Session>(),
38     REMOTE_CLUSTER_CONFIG: ofType<{ config: Config }>(),
39 });
40
41 export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
42     // Cancel any link account ops in progress unless the user has
43     // just logged in or there has been a successful link operation
44     const data = services.linkAccountService.getLinkOpStatus();
45     if (!matchTokenRoute(location.pathname) &&
46         (!matchFedTokenRoute(location.pathname)) && data === undefined) {
47         dispatch<any>(cancelLinking()).then(() => {
48             dispatch<any>(init(config));
49         });
50     } else {
51         dispatch<any>(init(config));
52     }
53 };
54
55 const init = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
56     const remoteHosts = () => getState().auth.remoteHosts;
57     const token = services.authService.getApiToken();
58     let homeCluster = services.authService.getHomeCluster();
59     if (homeCluster && !config.remoteHosts[homeCluster]) {
60         homeCluster = undefined;
61     }
62     dispatch(authActions.SET_CONFIG({ config }));
63     Object.keys(remoteHosts()).forEach((remoteUuid: string) => {
64         const remoteHost = remoteHosts()[remoteUuid];
65         if (remoteUuid !== config.uuidPrefix) {
66             dispatch<any>(addRemoteConfig(remoteHost));
67         }
68     });
69     dispatch(authActions.SET_HOME_CLUSTER(config.loginCluster || homeCluster || config.uuidPrefix));
70
71     if (token && token !== "undefined") {
72         dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
73         dispatch<any>(saveApiToken(token)).then(() => {
74             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
75         }).catch(() => {
76             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
77         });
78     }
79 };
80
81 export const getConfig = (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Config => {
82     const state = getState().auth;
83     return state.remoteHostsConfig[state.localCluster];
84 };
85
86 export const saveApiToken = (token: string) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
87     const config = dispatch<any>(getConfig);
88     const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
89     setAuthorizationHeader(svc, token);
90     try {
91         const user = await svc.authService.getUserDetails();
92         const client = await svc.apiClientAuthorizationService.get('current');
93         const tokenExpiration = client.expiresAt ? new Date(client.expiresAt) : undefined;
94         dispatch(authActions.INIT_USER({ user, token, tokenExpiration }));
95     } catch (e) {
96         dispatch(authActions.LOGOUT({ deleteLinkData: false }));
97     }
98 };
99
100 export const getNewExtraToken = (reuseStored: boolean = false) =>
101     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
102         const extraToken = getState().auth.extraApiToken;
103         if (reuseStored && extraToken !== undefined) {
104             const config = dispatch<any>(getConfig);
105             const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
106             setAuthorizationHeader(svc, extraToken);
107             try {
108                 // Check the extra token's validity before using it. Refresh its
109                 // expiration date just in case it changed.
110                 const client = await svc.apiClientAuthorizationService.get('current');
111                 dispatch(authActions.SET_EXTRA_TOKEN({
112                     extraApiToken: extraToken,
113                     extraApiTokenExpiration: client.expiresAt ? new Date(client.expiresAt): undefined,
114                 }));
115                 return extraToken;
116             } catch (e) {
117                 dispatch(authActions.RESET_EXTRA_TOKEN());
118             }
119         }
120         const user = getState().auth.user;
121         const loginCluster = getState().auth.config.clusterConfig.Login.LoginCluster;
122         if (user === undefined) { return; }
123         if (loginCluster !== "" && getState().auth.homeCluster !== loginCluster) { return; }
124         try {
125             // Do not show errors on the create call, cluster security configuration may not
126             // allow token creation and there's no way to know that from workbench2 side in advance.
127             const client = await services.apiClientAuthorizationService.create(undefined, false);
128             const newExtraToken = getTokenV2(client);
129             dispatch(authActions.SET_EXTRA_TOKEN({
130                 extraApiToken: newExtraToken,
131                 extraApiTokenExpiration: client.expiresAt ? new Date(client.expiresAt): undefined,
132             }));
133             return newExtraToken;
134         } catch {
135             console.warn("Cannot create new tokens with the current token, probably because of cluster's security settings.");
136             return;
137         }
138     };
139
140 export const login = (uuidPrefix: string, homeCluster: string, loginCluster: string,
141     remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
142         services.authService.login(uuidPrefix, homeCluster, loginCluster, remoteHosts);
143         dispatch(authActions.LOGIN());
144     };
145
146 export const logout = (deleteLinkData: boolean = false) =>
147     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) =>
148         dispatch(authActions.LOGOUT({ deleteLinkData }));
149
150 export type AuthAction = UnionOf<typeof authActions>;