1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
13 Config, ClusterConfigJSON, CLUSTER_CONFIG_PATH, DISCOVERY_DOC_PATH,
14 buildConfig, mockClusterConfigJSON
15 } from "~/common/config";
16 import { normalizeURLPath } from "~/common/url";
17 import { Session, SessionStatus } from "~/models/session";
18 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
19 import { AuthService, UserDetailsResponse } from "~/services/auth-service/auth-service";
20 import { snackbarActions, SnackbarKind } from "~/store/snackbar/snackbar-actions";
21 import * as jsSHA from "jssha";
23 const getClusterConfig = async (origin: string): Promise<Config | null> => {
24 // Try the new public config endpoint
26 const config = (await Axios.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
27 return buildConfig(config);
30 // Fall back to discovery document
32 const config = (await Axios.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
34 baseUrl: normalizeURLPath(config.baseUrl),
35 keepWebServiceUrl: config.keepWebServiceUrl,
36 remoteHosts: config.remoteHosts,
37 rootUrl: config.rootUrl,
38 uuidPrefix: config.uuidPrefix,
39 websocketUrl: config.websocketUrl,
40 workbenchUrl: config.workbenchUrl,
41 workbench2Url: config.workbench2Url,
44 fileViewersConfigUrl: "",
45 clusterConfig: mockClusterConfigJSON({})
52 const getRemoteHostConfig = async (remoteHost: string): Promise<Config | null> => {
54 if (url.indexOf('://') < 0) {
55 url = 'https://' + url;
57 const origin = new URL(url).origin;
59 // Maybe it is an API server URL, try fetching config and discovery doc
60 let r = await getClusterConfig(origin);
65 // Maybe it is a Workbench2 URL, try getting config.json
67 r = await getClusterConfig((await Axios.get<any>(`${origin}/config.json`)).data.API_HOST);
73 // Maybe it is a Workbench1 URL, try getting status.json
75 r = await getClusterConfig((await Axios.get<any>(`${origin}/status.json`)).data.apiBaseURL);
84 const getUserDetails = async (baseUrl: string, token: string): Promise<UserDetailsResponse> => {
85 const resp = await Axios.get<UserDetailsResponse>(`${baseUrl}/users/current`, {
87 Authorization: `OAuth2 ${token}`
93 const invalidV2Token = "Must be a v2 token";
95 export const getSaltedToken = (clusterId: string, token: string) => {
96 const shaObj = new jsSHA("SHA-1", "TEXT");
97 const [ver, uuid, secret] = token.split("/");
99 throw new Error(invalidV2Token);
102 if (uuid.substr(0, 5) !== clusterId) {
103 shaObj.setHMACKey(secret, "TEXT");
104 shaObj.update(clusterId);
105 salted = shaObj.getHMAC("HEX");
107 return `v2/${uuid}/${salted}`;
110 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
112 export const validateCluster = async (config: Config, useToken: string):
113 Promise<{ user: User; token: string }> => {
115 const saltedToken = getSaltedToken(config.uuidPrefix, useToken);
116 const user = await getUserDetails(config.baseUrl, saltedToken);
119 firstName: user.first_name,
120 lastName: user.last_name,
122 ownerUuid: user.owner_uuid,
124 isAdmin: user.is_admin,
125 isActive: user.is_active,
126 username: user.username,
133 export const validateSession = (session: Session, activeSession: Session) =>
134 async (dispatch: Dispatch): Promise<Session> => {
135 dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
136 session.loggedIn = false;
138 const setupSession = (baseUrl: string, user: User, token: string) => {
139 session.baseUrl = baseUrl;
140 session.token = token;
141 session.email = user.email;
142 session.uuid = user.uuid;
143 session.name = getUserFullname(user);
144 session.loggedIn = true;
147 let fail: Error | null = null;
148 const config = await getRemoteHostConfig(session.remoteHost);
149 if (config !== null) {
150 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
152 const { user, token } = await validateCluster(config, session.token);
153 setupSession(config.baseUrl, user, token);
155 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
157 const { user, token } = await validateCluster(config, activeSession.token);
158 setupSession(config.baseUrl, user, token);
161 if (e.message === invalidV2Token) {
162 fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
167 fail = new Error(`Could not get config for ${session.remoteHost}`);
169 session.status = SessionStatus.VALIDATED;
170 dispatch(authActions.UPDATE_SESSION(session));
179 export const validateSessions = () =>
180 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
181 const sessions = getState().auth.sessions;
182 const activeSession = getActiveSession(sessions);
184 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
185 for (const session of sessions) {
186 if (session.status === SessionStatus.INVALIDATED) {
188 /* Here we are dispatching a function, not an
189 action. This is legal (it calls the
190 function with a 'Dispatch' object as the
191 first parameter) but the typescript
192 annotations don't understand this case, so
193 we get an error from typescript unless
194 override it using Dispatch<any>. This
195 pattern is used in a bunch of different
196 places in Workbench2. */
197 await dispatch(validateSession(session, activeSession));
199 dispatch(snackbarActions.OPEN_SNACKBAR({
201 kind: SnackbarKind.ERROR
206 services.authService.saveSessions(getState().auth.sessions);
207 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
211 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
212 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
213 const sessions = getState().auth.sessions;
214 const activeSession = getActiveSession(sessions);
215 let useToken: string | null = null;
218 } else if (activeSession) {
219 useToken = activeSession.token;
223 const config = await getRemoteHostConfig(remoteHost);
225 dispatch(snackbarActions.OPEN_SNACKBAR({
226 message: `Could not get config for ${remoteHost}`,
227 kind: SnackbarKind.ERROR
233 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
234 const { user, token } = await validateCluster(config, useToken);
237 status: SessionStatus.VALIDATED,
240 name: getUserFullname(user),
242 baseUrl: config.baseUrl,
243 clusterId: config.uuidPrefix,
248 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
249 await dispatch(authActions.UPDATE_SESSION(session));
251 await dispatch(authActions.ADD_SESSION(session));
253 services.authService.saveSessions(getState().auth.sessions);
258 const rootUrl = new URL(config.baseUrl);
259 rootUrl.pathname = "";
260 window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
265 return Promise.reject(new Error("Could not validate cluster"));
269 export const removeSession = (clusterId: string) =>
270 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
271 await dispatch(authActions.REMOVE_SESSION(clusterId));
272 services.authService.saveSessions(getState().auth.sessions);
275 export const toggleSession = (session: Session) =>
276 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
277 const s: Session = { ...session };
279 if (session.loggedIn) {
281 dispatch(authActions.UPDATE_SESSION(s));
283 const sessions = getState().auth.sessions;
284 const activeSession = getActiveSession(sessions);
287 await dispatch(validateSession(s, activeSession));
289 dispatch(snackbarActions.OPEN_SNACKBAR({
291 kind: SnackbarKind.ERROR
294 dispatch(authActions.UPDATE_SESSION(s));
299 services.authService.saveSessions(getState().auth.sessions);
302 export const initSessions = (authService: AuthService, config: Config, user: User) =>
303 (dispatch: Dispatch<any>) => {
304 const sessions = authService.buildSessions(config, user);
305 dispatch(authActions.SET_SESSIONS(sessions));
306 dispatch(validateSessions());
309 export const loadSiteManagerPanel = () =>
310 async (dispatch: Dispatch<any>) => {
312 dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
313 dispatch(validateSessions());