Add login in/out handling, fix async validation
[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         },
96         token: saltedToken
97     };
98 };
99
100 const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
101
102 export const validateCluster = async (remoteHost: string, clusterId: string, activeSession: Session): Promise<{ user: User; token: string, baseUrl: string }> => {
103     const baseUrl = await getRemoteHostBaseUrl(remoteHost);
104     if (!baseUrl) {
105         return Promise.reject(`Could not find base url for ${remoteHost}`);
106     }
107     const { user, token } = await clusterLogin(clusterId, baseUrl, activeSession);
108     return { baseUrl, user, token };
109 };
110
111 export const validateSession = (session: Session, activeSession: Session) =>
112     async (dispatch: Dispatch): Promise<Session> => {
113         dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
114         session.loggedIn = false;
115         try {
116             const { baseUrl, user, token } = await validateCluster(session.remoteHost, session.clusterId, activeSession);
117             session.baseUrl = baseUrl;
118             session.token = token;
119             session.email = user.email;
120             session.username = getUserFullname(user);
121             session.loggedIn = true;
122         } catch {
123             session.loggedIn = false;
124         } finally {
125             session.status = SessionStatus.VALIDATED;
126             dispatch(authActions.UPDATE_SESSION(session));
127         }
128         return session;
129     };
130
131 export const validateSessions = () =>
132     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
133         const sessions = getState().auth.sessions;
134         const activeSession = getActiveSession(sessions);
135         if (activeSession) {
136             dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
137             for (const session of sessions) {
138                 if (session.status === SessionStatus.INVALIDATED) {
139                     await dispatch(validateSession(session, activeSession));
140                 }
141             }
142             services.authService.saveSessions(sessions);
143             dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
144         }
145     };
146
147 export const addSession = (remoteHost: string) =>
148     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
149         const sessions = getState().auth.sessions;
150         const activeSession = getActiveSession(sessions);
151         if (activeSession) {
152             const clusterId = remoteHost.match(/^(\w+)\./)![1];
153             if (sessions.find(s => s.clusterId === clusterId)) {
154                 return Promise.reject("Cluster already exists");
155             }
156             try {
157                 const { baseUrl, user, token } = await validateCluster(remoteHost, clusterId, activeSession);
158                 const session = {
159                     loggedIn: true,
160                     status: SessionStatus.VALIDATED,
161                     active: false,
162                     email: user.email,
163                     username: getUserFullname(user),
164                     remoteHost,
165                     baseUrl,
166                     clusterId,
167                     token
168                 };
169
170                 dispatch(authActions.ADD_SESSION(session));
171                 services.authService.saveSessions(getState().auth.sessions);
172
173                 return session;
174             } catch (e) {
175             }
176         }
177         return Promise.reject("Could not validate cluster");
178     };
179
180 export const toggleSession = (session: Session) =>
181     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
182         let s = { ...session };
183
184         if (session.loggedIn) {
185             s.loggedIn = false;
186         } else {
187             const sessions = getState().auth.sessions;
188             const activeSession = getActiveSession(sessions);
189             if (activeSession) {
190                 s = await dispatch<any>(validateSession(s, activeSession)) as Session;
191             }
192         }
193
194         dispatch(authActions.UPDATE_SESSION(s));
195         services.authService.saveSessions(getState().auth.sessions);
196     };
197
198 export const loadSiteManagerPanel = () =>
199     async (dispatch: Dispatch<any>) => {
200         try {
201             dispatch(setBreadcrumbs([{ label: 'Site Manager'}]));
202             dispatch(validateSessions());
203         } catch (e) {
204             return;
205         }
206     };