Merge branch 'origin/master' into 14478-log-in-into-clusters
[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, DISCOVERY_URL } from "~/common/config";
13 import { Session, SessionStatus } from "~/models/session";
14 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
15 import { UserDetailsResponse } from "~/services/auth-service/auth-service";
16 import * as jsSHA from "jssha";
17
18 const getRemoteHostBaseUrl = async (remoteHost: string): Promise<string | null> => {
19     let url = remoteHost;
20     if (url.indexOf('://') < 0) {
21         url = 'https://' + url;
22     }
23     const origin = new URL(url).origin;
24     let baseUrl: string | null = null;
25
26     try {
27         const resp = await Axios.get<Config>(`${origin}/${DISCOVERY_URL}`);
28         baseUrl = resp.data.baseUrl;
29     } catch (err) {
30         try {
31             const resp = await Axios.get<any>(`${origin}/status.json`);
32             baseUrl = resp.data.apiBaseURL;
33         } catch (err) {
34         }
35     }
36
37     if (baseUrl && baseUrl[baseUrl.length - 1] === '/') {
38         baseUrl = baseUrl.substr(0, baseUrl.length - 1);
39     }
40
41     return baseUrl;
42 };
43
44 const getUserDetails = async (baseUrl: string, token: string): Promise<UserDetailsResponse> => {
45     const resp = await Axios.get<UserDetailsResponse>(`${baseUrl}/users/current`, {
46         headers: {
47             Authorization: `OAuth2 ${token}`
48         }
49     });
50     return resp.data;
51 };
52
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);
57     }
58
59     const resp = await Axios.get(`${baseUrl}/api_client_authorizations`, {
60         headers: {
61             Authorization: `OAuth2 ${token}`
62         },
63         data: {
64             filters: JSON.stringify([['api_token', '=', token]])
65         }
66     });
67
68     return resp.data.items[0].uuid;
69 };
70
71 const getSaltedToken = (clusterId: string, tokenUuid: string, token: string) => {
72     const shaObj = new jsSHA("SHA-1", "TEXT");
73     let secret = token;
74     if (token.startsWith("v2/")) {
75         secret = token.split("/")[2];
76     }
77     shaObj.setHMACKey(secret, "TEXT");
78     shaObj.update(clusterId);
79     const hmac = shaObj.getHMAC("HEX");
80     return `v2/${tokenUuid}/${hmac}`;
81 };
82
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);
87     return {
88         user: {
89             firstName: user.first_name,
90             lastName: user.last_name,
91             uuid: user.uuid,
92             ownerUuid: user.owner_uuid,
93             email: user.email,
94             isAdmin: user.is_admin,
95             identityUrl: user.identity_url,
96             prefs: user.prefs
97         },
98         token: saltedToken
99     };
100 };
101
102 const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
103
104 export const validateCluster = async (remoteHost: string, clusterId: string, activeSession: Session): Promise<{ user: User; token: string, baseUrl: string }> => {
105     const baseUrl = await getRemoteHostBaseUrl(remoteHost);
106     if (!baseUrl) {
107         return Promise.reject(`Could not find base url for ${remoteHost}`);
108     }
109     const { user, token } = await clusterLogin(clusterId, baseUrl, activeSession);
110     return { baseUrl, user, token };
111 };
112
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;
117         try {
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;
124         } catch {
125             session.loggedIn = false;
126         } finally {
127             session.status = SessionStatus.VALIDATED;
128             dispatch(authActions.UPDATE_SESSION(session));
129         }
130         return session;
131     };
132
133 export const validateSessions = () =>
134     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
135         const sessions = getState().auth.sessions;
136         const activeSession = getActiveSession(sessions);
137         if (activeSession) {
138             dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
139             for (const session of sessions) {
140                 if (session.status === SessionStatus.INVALIDATED) {
141                     await dispatch(validateSession(session, activeSession));
142                 }
143             }
144             services.authService.saveSessions(sessions);
145             dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
146         }
147     };
148
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);
153         if (activeSession) {
154             const clusterId = remoteHost.match(/^(\w+)\./)![1];
155             if (sessions.find(s => s.clusterId === clusterId)) {
156                 return Promise.reject("Cluster already exists");
157             }
158             try {
159                 const { baseUrl, user, token } = await validateCluster(remoteHost, clusterId, activeSession);
160                 const session = {
161                     loggedIn: true,
162                     status: SessionStatus.VALIDATED,
163                     active: false,
164                     email: user.email,
165                     username: getUserFullname(user),
166                     remoteHost,
167                     baseUrl,
168                     clusterId,
169                     token
170                 };
171
172                 dispatch(authActions.ADD_SESSION(session));
173                 services.authService.saveSessions(getState().auth.sessions);
174
175                 return session;
176             } catch (e) {
177             }
178         }
179         return Promise.reject("Could not validate cluster");
180     };
181
182 export const toggleSession = (session: Session) =>
183     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
184         let s = { ...session };
185
186         if (session.loggedIn) {
187             s.loggedIn = false;
188         } else {
189             const sessions = getState().auth.sessions;
190             const activeSession = getActiveSession(sessions);
191             if (activeSession) {
192                 s = await dispatch<any>(validateSession(s, activeSession)) as Session;
193             }
194         }
195
196         dispatch(authActions.UPDATE_SESSION(s));
197         services.authService.saveSessions(getState().auth.sessions);
198     };
199
200 export const loadSiteManagerPanel = () =>
201     async (dispatch: Dispatch<any>) => {
202         try {
203             dispatch(setBreadcrumbs([{ label: 'Site Manager'}]));
204             dispatch(validateSessions());
205         } catch (e) {
206             return;
207         }
208     };