20251: Fix flaky collection file browser by using race-free state update callback
[arvados-workbench2.git] / src / services / auth-service / auth-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { User, UserPrefs, getUserDisplayName } from 'models/user';
6 import { AxiosInstance } from "axios";
7 import { ApiActions } from "services/api/api-actions";
8 import uuid from "uuid/v4";
9 import { Session, SessionStatus } from "models/session";
10 import { Config } from "common/config";
11 import { uniqBy } from "lodash";
12
13 export const TARGET_URL = 'targetURL';
14 export const API_TOKEN_KEY = 'apiToken';
15 export const USER_EMAIL_KEY = 'userEmail';
16 export const USER_FIRST_NAME_KEY = 'userFirstName';
17 export const USER_LAST_NAME_KEY = 'userLastName';
18 export const USER_UUID_KEY = 'userUuid';
19 export const USER_OWNER_UUID_KEY = 'userOwnerUuid';
20 export const USER_IS_ADMIN = 'isAdmin';
21 export const USER_IS_ACTIVE = 'isActive';
22 export const USER_USERNAME = 'username';
23 export const USER_PREFS = 'prefs';
24 export const HOME_CLUSTER = 'homeCluster';
25 export const LOCAL_STORAGE = 'localStorage';
26 export const SESSION_STORAGE = 'sessionStorage';
27
28 export interface UserDetailsResponse {
29     email: string;
30     first_name: string;
31     last_name: string;
32     uuid: string;
33     owner_uuid: string;
34     is_admin: boolean;
35     is_active: boolean;
36     username: string;
37     prefs: UserPrefs;
38 }
39
40 export class AuthService {
41
42     constructor(
43         protected apiClient: AxiosInstance,
44         protected baseUrl: string,
45         protected actions: ApiActions,
46         protected useSessionStorage: boolean = false) { }
47
48     private getStorage() {
49         if (this.useSessionStorage) {
50             return sessionStorage;
51         }
52         return localStorage;
53     }
54
55     public getStorageType() {
56         if (this.useSessionStorage) {
57             return SESSION_STORAGE;
58         }
59         return LOCAL_STORAGE;
60     }
61
62     public saveApiToken(token: string) {
63         this.removeApiToken();
64         this.getStorage().setItem(API_TOKEN_KEY, token);
65         const sp = token.split('/');
66         if (sp.length === 3) {
67             this.getStorage().setItem(HOME_CLUSTER, sp[1].substring(0, 5));
68         }
69     }
70
71     public setTargetUrl(url: string) {
72         localStorage.setItem(TARGET_URL, url);
73     }
74
75     public removeTargetURL() {
76         localStorage.removeItem(TARGET_URL);
77     }
78
79     public getTargetURL() {
80         return localStorage.getItem(TARGET_URL);
81     }
82
83     public removeApiToken() {
84         localStorage.removeItem(API_TOKEN_KEY);
85         sessionStorage.removeItem(API_TOKEN_KEY);
86     }
87
88     public getApiToken() {
89         return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
90     }
91
92     public getHomeCluster() {
93         return this.getStorage().getItem(HOME_CLUSTER) || undefined;
94     }
95
96     public getApiClient() {
97         return this.apiClient;
98     }
99
100     public removeUser() {
101         [localStorage, sessionStorage].forEach((storage) => {
102             storage.removeItem(USER_EMAIL_KEY);
103             storage.removeItem(USER_FIRST_NAME_KEY);
104             storage.removeItem(USER_LAST_NAME_KEY);
105             storage.removeItem(USER_UUID_KEY);
106             storage.removeItem(USER_OWNER_UUID_KEY);
107             storage.removeItem(USER_IS_ADMIN);
108             storage.removeItem(USER_IS_ACTIVE);
109             storage.removeItem(USER_USERNAME);
110             storage.removeItem(USER_PREFS);
111             storage.removeItem(TARGET_URL);
112         });
113     }
114
115     public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
116         const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
117         const homeClusterHost = remoteHosts[homeCluster];
118         const rd = new URL(window.location.href);
119         this.setTargetUrl(rd.pathname + rd.search);
120         window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
121     }
122
123     public logout(expireToken: string, preservePath: boolean) {
124         const fullUrl = new URL(window.location.href);
125         const wbBase = `${fullUrl.protocol}//${fullUrl.host}`;
126         const wbPath = fullUrl.pathname + fullUrl.search;
127         const returnTo = `${wbBase}${preservePath ? wbPath : ''}`
128
129         window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${returnTo}`);
130     }
131
132     public getUserDetails = (showErrors?: boolean): Promise<User> => {
133         const reqId = uuid();
134         this.actions.progressFn(reqId, true);
135         return this.apiClient
136             .get<UserDetailsResponse>('/users/current')
137             .then(resp => {
138                 this.actions.progressFn(reqId, false);
139                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
140                 return {
141                     email: resp.data.email,
142                     firstName: resp.data.first_name,
143                     lastName: resp.data.last_name,
144                     uuid: resp.data.uuid,
145                     ownerUuid: resp.data.owner_uuid,
146                     isAdmin: resp.data.is_admin,
147                     isActive: resp.data.is_active,
148                     username: resp.data.username,
149                     prefs
150                 };
151             })
152             .catch(e => {
153                 this.actions.progressFn(reqId, false);
154                 this.actions.errorFn(reqId, e, showErrors);
155                 throw e;
156             });
157     }
158
159     public getSessions(): Session[] {
160         try {
161             const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
162             return sessions;
163         } catch {
164             return [];
165         }
166     }
167
168     public saveSessions(sessions: Session[]) {
169         this.removeSessions();
170         this.getStorage().setItem("sessions", JSON.stringify(sessions));
171     }
172
173     public removeSessions() {
174         localStorage.removeItem("sessions");
175         sessionStorage.removeItem("sessions");
176     }
177
178     public buildSessions(cfg: Config, user?: User) {
179         const currentSession = {
180             clusterId: cfg.uuidPrefix,
181             remoteHost: cfg.rootUrl,
182             baseUrl: cfg.baseUrl,
183             name: user ? getUserDisplayName(user) : '',
184             email: user ? user.email : '',
185             userIsActive: user ? user.isActive : false,
186             token: this.getApiToken(),
187             loggedIn: true,
188             active: true,
189             uuid: user ? user.uuid : '',
190             status: SessionStatus.VALIDATED,
191             apiRevision: cfg.apiRevision,
192         } as Session;
193         const localSessions = this.getSessions().map(s => ({
194             ...s,
195             active: false,
196             status: SessionStatus.INVALIDATED
197         }));
198
199         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
200             const remoteHost = cfg.remoteHosts[clusterId];
201             return {
202                 clusterId,
203                 remoteHost,
204                 baseUrl: '',
205                 name: '',
206                 email: '',
207                 token: '',
208                 loggedIn: false,
209                 active: false,
210                 uuid: '',
211                 status: SessionStatus.INVALIDATED,
212                 apiRevision: 0,
213             } as Session;
214         });
215         const sessions = [currentSession]
216             .concat(cfgSessions)
217             .concat(localSessions)
218             .filter((r: Session) => r.clusterId !== "*");
219
220         const uniqSessions = uniqBy(sessions, 'clusterId');
221
222         return uniqSessions;
223     }
224 }