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, DISCOVERY_URL } from "~/common/config";
13 import { Session, SessionStatus } from "~/models/session";
14 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
15 import { AuthService, UserDetailsResponse } from "~/services/auth-service/auth-service";
16 import * as jsSHA from "jssha";
18 const getRemoteHostBaseUrl = async (remoteHost: string): Promise<string | null> => {
20 if (url.indexOf('://') < 0) {
21 url = 'https://' + url;
23 const origin = new URL(url).origin;
24 let baseUrl: string | null = null;
27 const resp = await Axios.get<Config>(`${origin}/${DISCOVERY_URL}`);
28 baseUrl = resp.data.baseUrl;
31 const resp = await Axios.get<any>(`${origin}/status.json`);
32 baseUrl = resp.data.apiBaseURL;
37 if (baseUrl && baseUrl[baseUrl.length - 1] === '/') {
38 baseUrl = baseUrl.substr(0, baseUrl.length - 1);
44 const getUserDetails = async (baseUrl: string, token: string): Promise<UserDetailsResponse> => {
45 const resp = await Axios.get<UserDetailsResponse>(`${baseUrl}/users/current`, {
47 Authorization: `OAuth2 ${token}`
53 const getTokenUuid = async (baseUrl: string, token: string): Promise<string> => {
54 if (token.startsWith("v2/")) {
55 const uuid = token.split("/")[1];
56 return Promise.resolve(uuid);
59 const resp = await Axios.get(`${baseUrl}/api_client_authorizations`, {
61 Authorization: `OAuth2 ${token}`
64 filters: JSON.stringify([['api_token', '=', token]])
68 return resp.data.items[0].uuid;
71 const getSaltedToken = (clusterId: string, tokenUuid: string, token: string) => {
72 const shaObj = new jsSHA("SHA-1", "TEXT");
74 if (token.startsWith("v2/")) {
75 secret = token.split("/")[2];
77 shaObj.setHMACKey(secret, "TEXT");
78 shaObj.update(clusterId);
79 const hmac = shaObj.getHMAC("HEX");
80 return `v2/${tokenUuid}/${hmac}`;
83 const clusterLogin = async (clusterId: string, baseUrl: string, activeSession: Session): Promise<{user: User, token: string}> => {
84 const tokenUuid = await getTokenUuid(activeSession.baseUrl, activeSession.token);
85 const saltedToken = getSaltedToken(clusterId, tokenUuid, activeSession.token);
86 const user = await getUserDetails(baseUrl, saltedToken);
89 firstName: user.first_name,
90 lastName: user.last_name,
92 ownerUuid: user.owner_uuid,
94 isAdmin: user.is_admin,
95 identityUrl: user.identity_url,
102 const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
104 export const validateCluster = async (remoteHost: string, clusterId: string, activeSession: Session): Promise<{ user: User; token: string, baseUrl: string }> => {
105 const baseUrl = await getRemoteHostBaseUrl(remoteHost);
107 return Promise.reject(`Could not find base url for ${remoteHost}`);
109 const { user, token } = await clusterLogin(clusterId, baseUrl, activeSession);
110 return { baseUrl, user, token };
113 export const validateSession = (session: Session, activeSession: Session) =>
114 async (dispatch: Dispatch): Promise<Session> => {
115 dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
116 session.loggedIn = false;
118 const { baseUrl, user, token } = await validateCluster(session.remoteHost, session.clusterId, activeSession);
119 session.baseUrl = baseUrl;
120 session.token = token;
121 session.email = user.email;
122 session.username = getUserFullname(user);
123 session.loggedIn = true;
125 session.loggedIn = false;
127 session.status = SessionStatus.VALIDATED;
128 dispatch(authActions.UPDATE_SESSION(session));
133 export const validateSessions = () =>
134 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
135 const sessions = getState().auth.sessions;
136 const activeSession = getActiveSession(sessions);
138 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
139 for (const session of sessions) {
140 if (session.status === SessionStatus.INVALIDATED) {
141 await dispatch(validateSession(session, activeSession));
144 services.authService.saveSessions(sessions);
145 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
149 export const addSession = (remoteHost: string) =>
150 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
151 const sessions = getState().auth.sessions;
152 const activeSession = getActiveSession(sessions);
154 const clusterId = remoteHost.match(/^(\w+)\./)![1];
155 if (sessions.find(s => s.clusterId === clusterId)) {
156 return Promise.reject("Cluster already exists");
159 const { baseUrl, user, token } = await validateCluster(remoteHost, clusterId, activeSession);
162 status: SessionStatus.VALIDATED,
165 username: getUserFullname(user),
172 dispatch(authActions.ADD_SESSION(session));
173 services.authService.saveSessions(getState().auth.sessions);
179 return Promise.reject("Could not validate cluster");
182 export const toggleSession = (session: Session) =>
183 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
184 let s = { ...session };
186 if (session.loggedIn) {
189 const sessions = getState().auth.sessions;
190 const activeSession = getActiveSession(sessions);
192 s = await dispatch<any>(validateSession(s, activeSession)) as Session;
196 dispatch(authActions.UPDATE_SESSION(s));
197 services.authService.saveSessions(getState().auth.sessions);
200 export const initSessions = (authService: AuthService, config: Config, user: User) =>
201 (dispatch: Dispatch<any>) => {
202 const sessions = authService.buildSessions(config, user);
203 authService.saveSessions(sessions);
204 dispatch(authActions.SET_SESSIONS(sessions));
207 export const loadSiteManagerPanel = () =>
208 async (dispatch: Dispatch<any>) => {
210 dispatch(setBreadcrumbs([{ label: 'Site Manager'}]));
211 dispatch(validateSessions());