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";
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";
20 const getClusterInfo = async (origin: string): Promise<{ clusterId: string, baseUrl: string } | null> => {
21 // Try the new public config endpoint
23 const config = (await Axios.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
25 clusterId: config.ClusterID,
26 baseUrl: normalizeURLPath(`${config.Services.Controller.ExternalURL}/${ARVADOS_API_PATH}`)
30 // Fall back to discovery document
32 const config = (await Axios.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
34 clusterId: config.uuidPrefix,
35 baseUrl: normalizeURLPath(config.baseUrl)
42 interface RemoteHostInfo {
47 const getRemoteHostInfo = async (remoteHost: string): Promise<RemoteHostInfo | null> => {
49 if (url.indexOf('://') < 0) {
50 url = 'https://' + url;
52 const origin = new URL(url).origin;
54 // Maybe it is an API server URL, try fetching config and discovery doc
55 let r = getClusterInfo(origin);
60 // Maybe it is a Workbench2 URL, try getting config.json
62 r = getClusterInfo((await Axios.get<any>(`${origin}/config.json`)).data.API_HOST);
68 // Maybe it is a Workbench1 URL, try getting status.json
70 r = getClusterInfo((await Axios.get<any>(`${origin}/status.json`)).data.apiBaseURL);
79 const getUserDetails = async (baseUrl: string, token: string): Promise<UserDetailsResponse> => {
80 const resp = await Axios.get<UserDetailsResponse>(`${baseUrl}/users/current`, {
82 Authorization: `OAuth2 ${token}`
88 const invalidV2Token = "Must be a v2 token";
90 export const getSaltedToken = (clusterId: string, token: string) => {
91 const shaObj = new jsSHA("SHA-1", "TEXT");
92 const [ver, uuid, secret] = token.split("/");
94 throw new Error(invalidV2Token);
97 if (uuid.substr(0, 5) !== clusterId) {
98 shaObj.setHMACKey(secret, "TEXT");
99 shaObj.update(clusterId);
100 salted = shaObj.getHMAC("HEX");
102 return `v2/${uuid}/${salted}`;
105 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
107 export const validateCluster = async (info: RemoteHostInfo, useToken: string):
108 Promise<{ user: User; token: string }> => {
110 const saltedToken = getSaltedToken(info.clusterId, useToken);
111 const user = await getUserDetails(info.baseUrl, saltedToken);
114 firstName: user.first_name,
115 lastName: user.last_name,
117 ownerUuid: user.owner_uuid,
119 isAdmin: user.is_admin,
120 isActive: user.is_active,
121 username: user.username,
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;
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;
142 const info = await getRemoteHostInfo(session.remoteHost);
144 throw new Error(`Could not get config for ${session.remoteHost}`);
147 let fail: Error | null = null;
149 const { user, token } = await validateCluster(info, session.token);
150 setupSession(info.baseUrl, user, token);
152 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
154 const { user, token } = await validateCluster(info, activeSession.token);
155 setupSession(info.baseUrl, user, token);
158 if (e.message === invalidV2Token) {
159 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
164 session.status = SessionStatus.VALIDATED;
165 dispatch(authActions.UPDATE_SESSION(session));
174 export const validateSessions = () =>
175 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
176 const sessions = getState().auth.sessions;
177 const activeSession = getActiveSession(sessions);
179 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
180 for (const session of sessions) {
181 if (session.status === SessionStatus.INVALIDATED) {
183 /* Here we are dispatching a function, not an
184 action. This is legal (it calls the
185 function with a 'Dispatch' object as the
186 first parameter) but the typescript
187 annotations don't understand this case, so
188 we get an error from typescript unless
189 override it using Dispatch<any>. This
190 pattern is used in a bunch of different
191 places in Workbench2. */
192 await dispatch(validateSession(session, activeSession));
194 dispatch(snackbarActions.OPEN_SNACKBAR({
196 kind: SnackbarKind.ERROR
201 services.authService.saveSessions(sessions);
202 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
206 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
207 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
208 const sessions = getState().auth.sessions;
209 const activeSession = getActiveSession(sessions);
210 let useToken: string | null = null;
213 } else if (activeSession) {
214 useToken = activeSession.token;
218 const info = await getRemoteHostInfo(remoteHost);
220 dispatch(snackbarActions.OPEN_SNACKBAR({
221 message: `Could not get config for ${remoteHost}`,
222 kind: SnackbarKind.ERROR
228 const { user, token } = await validateCluster(info, useToken);
231 status: SessionStatus.VALIDATED,
234 name: getUserFullname(user),
236 baseUrl: info.baseUrl,
237 clusterId: info.clusterId,
242 if (sessions.find(s => s.clusterId === info.clusterId)) {
243 dispatch(authActions.UPDATE_SESSION(session));
245 dispatch(authActions.ADD_SESSION(session));
247 services.authService.saveSessions(getState().auth.sessions);
252 const rootUrl = new URL(info.baseUrl);
253 rootUrl.pathname = "";
254 window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
259 return Promise.reject(new Error("Could not validate cluster"));
262 export const toggleSession = (session: Session) =>
263 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
264 const s: Session = { ...session };
266 if (session.loggedIn) {
268 dispatch(authActions.UPDATE_SESSION(s));
270 const sessions = getState().auth.sessions;
271 const activeSession = getActiveSession(sessions);
274 await dispatch(validateSession(s, activeSession));
276 dispatch(snackbarActions.OPEN_SNACKBAR({
278 kind: SnackbarKind.ERROR
281 dispatch(authActions.UPDATE_SESSION(s));
286 services.authService.saveSessions(getState().auth.sessions);
289 export const initSessions = (authService: AuthService, config: Config, user: User) =>
290 (dispatch: Dispatch<any>) => {
291 const sessions = authService.buildSessions(config, user);
292 authService.saveSessions(sessions);
293 dispatch(authActions.SET_SESSIONS(sessions));
294 dispatch(validateSessions());
297 export const loadSiteManagerPanel = () =>
298 async (dispatch: Dispatch<any>) => {
300 dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
301 dispatch(validateSessions());