19231: Add smaller page sizes (10 and 20 items) to load faster
[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, getRemoteHostConfig } 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, tokenLocation?: string }>(),
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) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
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(window.location.pathname) &&
46         (!matchFedTokenRoute(window.location.pathname)) && data === undefined) {
47         await dispatch<any>(cancelLinking());
48     }
49     return dispatch<any>(init(config));
50 };
51
52 const init = (config: Config) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
53     const remoteHosts = () => getState().auth.remoteHosts;
54     const token = services.authService.getApiToken();
55     let homeCluster = services.authService.getHomeCluster();
56     if (homeCluster && !config.remoteHosts[homeCluster]) {
57         homeCluster = undefined;
58     }
59     dispatch(authActions.SET_CONFIG({ config }));
60     Object.keys(remoteHosts()).forEach((remoteUuid: string) => {
61         const remoteHost = remoteHosts()[remoteUuid];
62         if (remoteUuid !== config.uuidPrefix) {
63             dispatch<any>(addRemoteConfig(remoteHost));
64         }
65     });
66     dispatch(authActions.SET_HOME_CLUSTER(config.loginCluster || homeCluster || config.uuidPrefix));
67
68     if (token && token !== "undefined") {
69         dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
70         try {
71             await dispatch<any>(saveApiToken(token));
72         } finally {
73             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
74         }
75     }
76 };
77
78 export const getConfig = (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Config => {
79     const state = getState().auth;
80     return state.remoteHostsConfig[state.localCluster];
81 };
82
83 export const getLocalCluster = (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): string => {
84     return getState().auth.localCluster;
85 };
86
87 export const saveApiToken = (token: string) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
88     let config: any;
89     const tokenParts = token.split('/');
90     const auth = getState().auth;
91     config = dispatch<any>(getConfig);
92
93     // If the token is from a LoginCluster federation, get user & token data
94     // from the token issuing cluster.
95     const lc = (config as Config).loginCluster
96     const tokenCluster = tokenParts.length === 3
97         ? tokenParts[1].substring(0, 5)
98         : undefined;
99     if (tokenCluster && tokenCluster !== auth.localCluster &&
100         lc && lc === tokenCluster) {
101         config = await getRemoteHostConfig(auth.remoteHosts[tokenCluster]);
102     }
103
104     const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
105     setAuthorizationHeader(svc, token);
106     try {
107         const user = await svc.authService.getUserDetails();
108         const client = await svc.apiClientAuthorizationService.get('current');
109         const tokenExpiration = client.expiresAt ? new Date(client.expiresAt) : undefined;
110         const tokenLocation = await svc.authService.getStorageType();
111         dispatch(authActions.INIT_USER({ user, token, tokenExpiration, tokenLocation }));
112     } catch (e) {
113         dispatch(authActions.LOGOUT({ deleteLinkData: false }));
114     }
115 };
116
117 export const getNewExtraToken = (reuseStored: boolean = false) =>
118     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
119         const extraToken = getState().auth.extraApiToken;
120         if (reuseStored && extraToken !== undefined) {
121             const config = dispatch<any>(getConfig);
122             const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
123             setAuthorizationHeader(svc, extraToken);
124             try {
125                 // Check the extra token's validity before using it. Refresh its
126                 // expiration date just in case it changed.
127                 const client = await svc.apiClientAuthorizationService.get('current');
128                 dispatch(authActions.SET_EXTRA_TOKEN({
129                     extraApiToken: extraToken,
130                     extraApiTokenExpiration: client.expiresAt ? new Date(client.expiresAt): undefined,
131                 }));
132                 return extraToken;
133             } catch (e) {
134                 dispatch(authActions.RESET_EXTRA_TOKEN());
135             }
136         }
137         const user = getState().auth.user;
138         const loginCluster = getState().auth.config.clusterConfig.Login.LoginCluster;
139         if (user === undefined) { return; }
140         if (loginCluster !== "" && getState().auth.homeCluster !== loginCluster) { return; }
141         try {
142             // Do not show errors on the create call, cluster security configuration may not
143             // allow token creation and there's no way to know that from workbench2 side in advance.
144             const client = await services.apiClientAuthorizationService.create(undefined, false);
145             const newExtraToken = getTokenV2(client);
146             dispatch(authActions.SET_EXTRA_TOKEN({
147                 extraApiToken: newExtraToken,
148                 extraApiTokenExpiration: client.expiresAt ? new Date(client.expiresAt): undefined,
149             }));
150             return newExtraToken;
151         } catch {
152             console.warn("Cannot create new tokens with the current token, probably because of cluster's security settings.");
153             return;
154         }
155     };
156
157 export const login = (uuidPrefix: string, homeCluster: string, loginCluster: string,
158     remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
159         services.authService.login(uuidPrefix, homeCluster, loginCluster, remoteHosts);
160         dispatch(authActions.LOGIN());
161     };
162
163 export const logout = (deleteLinkData: boolean = false) =>
164     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) =>
165         dispatch(authActions.LOGOUT({ deleteLinkData }));
166
167 export type AuthAction = UnionOf<typeof authActions>;