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 let fail: Error | null = null;
143 const info = await getRemoteHostInfo(session.remoteHost);
146 const { user, token } = await validateCluster(info, session.token);
147 setupSession(info.baseUrl, user, token);
149 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
151 const { user, token } = await validateCluster(info, activeSession.token);
152 setupSession(info.baseUrl, user, token);
155 if (e.message === invalidV2Token) {
156 fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
161 fail = new Error(`Could not get config for ${session.remoteHost}`);
163 session.status = SessionStatus.VALIDATED;
164 dispatch(authActions.UPDATE_SESSION(session));
173 export const validateSessions = () =>
174 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
175 const sessions = getState().auth.sessions;
176 const activeSession = getActiveSession(sessions);
178 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
179 for (const session of sessions) {
180 if (session.status === SessionStatus.INVALIDATED) {
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));
193 dispatch(snackbarActions.OPEN_SNACKBAR({
195 kind: SnackbarKind.ERROR
200 services.authService.saveSessions(sessions);
201 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
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;
212 } else if (activeSession) {
213 useToken = activeSession.token;
217 const info = await getRemoteHostInfo(remoteHost);
219 dispatch(snackbarActions.OPEN_SNACKBAR({
220 message: `Could not get config for ${remoteHost}`,
221 kind: SnackbarKind.ERROR
227 const { user, token } = await validateCluster(info, useToken);
230 status: SessionStatus.VALIDATED,
233 name: getUserFullname(user),
235 baseUrl: info.baseUrl,
236 clusterId: info.clusterId,
241 if (sessions.find(s => s.clusterId === info.clusterId)) {
242 dispatch(authActions.UPDATE_SESSION(session));
244 dispatch(authActions.ADD_SESSION(session));
246 services.authService.saveSessions(getState().auth.sessions);
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()));
258 return Promise.reject(new Error("Could not validate cluster"));
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);
268 export const toggleSession = (session: Session) =>
269 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
270 const s: Session = { ...session };
272 if (session.loggedIn) {
274 dispatch(authActions.UPDATE_SESSION(s));
276 const sessions = getState().auth.sessions;
277 const activeSession = getActiveSession(sessions);
280 await dispatch(validateSession(s, activeSession));
282 dispatch(snackbarActions.OPEN_SNACKBAR({
284 kind: SnackbarKind.ERROR
287 dispatch(authActions.UPDATE_SESSION(s));
292 services.authService.saveSessions(getState().auth.sessions);
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());
303 export const loadSiteManagerPanel = () =>
304 async (dispatch: Dispatch<any>) => {
306 dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
307 dispatch(validateSessions());