15736: Add delete button to site manager
[arvados-workbench2.git] / src / store / auth / auth-action-session.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from "redux";
6 import { setBreadcrumbs } from "~/store/breadcrumbs/breadcrumbs-actions";
7 import { RootState } from "~/store/store";
8 import { ServiceRepository } from "~/services/services";
9 import Axios from "axios";
10 import { getUserFullname, User } from "~/models/user";
11 import { authActions } from "~/store/auth/auth-action";
12 import { Config, ClusterConfigJSON, CLUSTER_CONFIG_PATH, DISCOVERY_DOC_PATH, ARVADOS_API_PATH } from "~/common/config";
13 import { normalizeURLPath } from "~/common/url";
14 import { Session, SessionStatus } from "~/models/session";
15 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
16 import { AuthService, UserDetailsResponse } from "~/services/auth-service/auth-service";
17 import { snackbarActions, SnackbarKind } from "~/store/snackbar/snackbar-actions";
18 import * as jsSHA from "jssha";
19
20 const getClusterInfo = async (origin: string): Promise<{ clusterId: string, baseUrl: string } | null> => {
21     // Try the new public config endpoint
22     try {
23         const config = (await Axios.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
24         return {
25             clusterId: config.ClusterID,
26             baseUrl: normalizeURLPath(`${config.Services.Controller.ExternalURL}/${ARVADOS_API_PATH}`)
27         };
28     } catch { }
29
30     // Fall back to discovery document
31     try {
32         const config = (await Axios.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
33         return {
34             clusterId: config.uuidPrefix,
35             baseUrl: normalizeURLPath(config.baseUrl)
36         };
37     } catch { }
38
39     return null;
40 };
41
42 interface RemoteHostInfo {
43     clusterId: string;
44     baseUrl: string;
45 }
46
47 const getRemoteHostInfo = async (remoteHost: string): Promise<RemoteHostInfo | null> => {
48     let url = remoteHost;
49     if (url.indexOf('://') < 0) {
50         url = 'https://' + url;
51     }
52     const origin = new URL(url).origin;
53
54     // Maybe it is an API server URL, try fetching config and discovery doc
55     let r = getClusterInfo(origin);
56     if (r !== null) {
57         return r;
58     }
59
60     // Maybe it is a Workbench2 URL, try getting config.json
61     try {
62         r = getClusterInfo((await Axios.get<any>(`${origin}/config.json`)).data.API_HOST);
63         if (r !== null) {
64             return r;
65         }
66     } catch { }
67
68     // Maybe it is a Workbench1 URL, try getting status.json
69     try {
70         r = getClusterInfo((await Axios.get<any>(`${origin}/status.json`)).data.apiBaseURL);
71         if (r !== null) {
72             return r;
73         }
74     } catch { }
75
76     return null;
77 };
78
79 const getUserDetails = async (baseUrl: string, token: string): Promise<UserDetailsResponse> => {
80     const resp = await Axios.get<UserDetailsResponse>(`${baseUrl}/users/current`, {
81         headers: {
82             Authorization: `OAuth2 ${token}`
83         }
84     });
85     return resp.data;
86 };
87
88 const invalidV2Token = "Must be a v2 token";
89
90 export const getSaltedToken = (clusterId: string, token: string) => {
91     const shaObj = new jsSHA("SHA-1", "TEXT");
92     const [ver, uuid, secret] = token.split("/");
93     if (ver !== "v2") {
94         throw new Error(invalidV2Token);
95     }
96     let salted = secret;
97     if (uuid.substr(0, 5) !== clusterId) {
98         shaObj.setHMACKey(secret, "TEXT");
99         shaObj.update(clusterId);
100         salted = shaObj.getHMAC("HEX");
101     }
102     return `v2/${uuid}/${salted}`;
103 };
104
105 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
106
107 export const validateCluster = async (info: RemoteHostInfo, useToken: string):
108     Promise<{ user: User; token: string }> => {
109
110     const saltedToken = getSaltedToken(info.clusterId, useToken);
111     const user = await getUserDetails(info.baseUrl, saltedToken);
112     return {
113         user: {
114             firstName: user.first_name,
115             lastName: user.last_name,
116             uuid: user.uuid,
117             ownerUuid: user.owner_uuid,
118             email: user.email,
119             isAdmin: user.is_admin,
120             isActive: user.is_active,
121             username: user.username,
122             prefs: user.prefs
123         },
124         token: saltedToken,
125     };
126 };
127
128 export const validateSession = (session: Session, activeSession: Session) =>
129     async (dispatch: Dispatch): Promise<Session> => {
130         dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
131         session.loggedIn = false;
132
133         const setupSession = (baseUrl: string, user: User, token: string) => {
134             session.baseUrl = baseUrl;
135             session.token = token;
136             session.email = user.email;
137             session.uuid = user.uuid;
138             session.name = getUserFullname(user);
139             session.loggedIn = true;
140         };
141
142         let fail: Error | null = null;
143         const info = await getRemoteHostInfo(session.remoteHost);
144         if (info !== null) {
145             try {
146                 const { user, token } = await validateCluster(info, session.token);
147                 setupSession(info.baseUrl, user, token);
148             } catch (e) {
149                 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
150                 try {
151                     const { user, token } = await validateCluster(info, activeSession.token);
152                     setupSession(info.baseUrl, user, token);
153                     fail = null;
154                 } catch (e2) {
155                     if (e.message === invalidV2Token) {
156                         fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
157                     }
158                 }
159             }
160         } else {
161             fail = new Error(`Could not get config for ${session.remoteHost}`);
162         }
163         session.status = SessionStatus.VALIDATED;
164         dispatch(authActions.UPDATE_SESSION(session));
165
166         if (fail) {
167             throw fail;
168         }
169
170         return session;
171     };
172
173 export const validateSessions = () =>
174     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
175         const sessions = getState().auth.sessions;
176         const activeSession = getActiveSession(sessions);
177         if (activeSession) {
178             dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
179             for (const session of sessions) {
180                 if (session.status === SessionStatus.INVALIDATED) {
181                     try {
182                         /* Here we are dispatching a function, not an
183                            action.  This is legal (it calls the
184                            function with a 'Dispatch' object as the
185                            first parameter) but the typescript
186                            annotations don't understand this case, so
187                            we get an error from typescript unless
188                            override it using Dispatch<any>.  This
189                            pattern is used in a bunch of different
190                            places in Workbench2. */
191                         await dispatch(validateSession(session, activeSession));
192                     } catch (e) {
193                         dispatch(snackbarActions.OPEN_SNACKBAR({
194                             message: e.message,
195                             kind: SnackbarKind.ERROR
196                         }));
197                     }
198                 }
199             }
200             services.authService.saveSessions(sessions);
201             dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
202         }
203     };
204
205 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
206     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
207         const sessions = getState().auth.sessions;
208         const activeSession = getActiveSession(sessions);
209         let useToken: string | null = null;
210         if (token) {
211             useToken = token;
212         } else if (activeSession) {
213             useToken = activeSession.token;
214         }
215
216         if (useToken) {
217             const info = await getRemoteHostInfo(remoteHost);
218             if (!info) {
219                 dispatch(snackbarActions.OPEN_SNACKBAR({
220                     message: `Could not get config for ${remoteHost}`,
221                     kind: SnackbarKind.ERROR
222                 }));
223                 return;
224             }
225
226             try {
227                 const { user, token } = await validateCluster(info, useToken);
228                 const session = {
229                     loggedIn: true,
230                     status: SessionStatus.VALIDATED,
231                     active: false,
232                     email: user.email,
233                     name: getUserFullname(user),
234                     uuid: user.uuid,
235                     baseUrl: info.baseUrl,
236                     clusterId: info.clusterId,
237                     remoteHost,
238                     token
239                 };
240
241                 if (sessions.find(s => s.clusterId === info.clusterId)) {
242                     dispatch(authActions.UPDATE_SESSION(session));
243                 } else {
244                     dispatch(authActions.ADD_SESSION(session));
245                 }
246                 services.authService.saveSessions(getState().auth.sessions);
247
248                 return session;
249             } catch {
250                 if (sendToLogin) {
251                     const rootUrl = new URL(info.baseUrl);
252                     rootUrl.pathname = "";
253                     window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
254                     return;
255                 }
256             }
257         }
258         return Promise.reject(new Error("Could not validate cluster"));
259     };
260
261
262 export const removeSession = (clusterId: string) =>
263     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
264         await dispatch(authActions.REMOVE_SESSION(clusterId));
265         services.authService.saveSessions(getState().auth.sessions);
266     };
267
268 export const toggleSession = (session: Session) =>
269     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
270         const s: Session = { ...session };
271
272         if (session.loggedIn) {
273             s.loggedIn = false;
274             dispatch(authActions.UPDATE_SESSION(s));
275         } else {
276             const sessions = getState().auth.sessions;
277             const activeSession = getActiveSession(sessions);
278             if (activeSession) {
279                 try {
280                     await dispatch(validateSession(s, activeSession));
281                 } catch (e) {
282                     dispatch(snackbarActions.OPEN_SNACKBAR({
283                         message: e.message,
284                         kind: SnackbarKind.ERROR
285                     }));
286                     s.loggedIn = false;
287                     dispatch(authActions.UPDATE_SESSION(s));
288                 }
289             }
290         }
291
292         services.authService.saveSessions(getState().auth.sessions);
293     };
294
295 export const initSessions = (authService: AuthService, config: Config, user: User) =>
296     (dispatch: Dispatch<any>) => {
297         const sessions = authService.buildSessions(config, user);
298         authService.saveSessions(sessions);
299         dispatch(authActions.SET_SESSIONS(sessions));
300         dispatch(validateSessions());
301     };
302
303 export const loadSiteManagerPanel = () =>
304     async (dispatch: Dispatch<any>) => {
305         try {
306             dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
307             dispatch(validateSessions());
308         } catch (e) {
309             return;
310         }
311     };