19231: Add smaller page sizes (10 and 20 items) to load faster
[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) {
124         const currentUrl = `${window.location.protocol}//${window.location.host}`;
125         window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${currentUrl}`);
126     }
127
128     public getUserDetails = (showErrors?: boolean): Promise<User> => {
129         const reqId = uuid();
130         this.actions.progressFn(reqId, true);
131         return this.apiClient
132             .get<UserDetailsResponse>('/users/current')
133             .then(resp => {
134                 this.actions.progressFn(reqId, false);
135                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
136                 return {
137                     email: resp.data.email,
138                     firstName: resp.data.first_name,
139                     lastName: resp.data.last_name,
140                     uuid: resp.data.uuid,
141                     ownerUuid: resp.data.owner_uuid,
142                     isAdmin: resp.data.is_admin,
143                     isActive: resp.data.is_active,
144                     username: resp.data.username,
145                     prefs
146                 };
147             })
148             .catch(e => {
149                 this.actions.progressFn(reqId, false);
150                 this.actions.errorFn(reqId, e, showErrors);
151                 throw e;
152             });
153     }
154
155     public getSessions(): Session[] {
156         try {
157             const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
158             return sessions;
159         } catch {
160             return [];
161         }
162     }
163
164     public saveSessions(sessions: Session[]) {
165         this.removeSessions();
166         this.getStorage().setItem("sessions", JSON.stringify(sessions));
167     }
168
169     public removeSessions() {
170         localStorage.removeItem("sessions");
171         sessionStorage.removeItem("sessions");
172     }
173
174     public buildSessions(cfg: Config, user?: User) {
175         const currentSession = {
176             clusterId: cfg.uuidPrefix,
177             remoteHost: cfg.rootUrl,
178             baseUrl: cfg.baseUrl,
179             name: user ? getUserDisplayName(user) : '',
180             email: user ? user.email : '',
181             userIsActive: user ? user.isActive : false,
182             token: this.getApiToken(),
183             loggedIn: true,
184             active: true,
185             uuid: user ? user.uuid : '',
186             status: SessionStatus.VALIDATED,
187             apiRevision: cfg.apiRevision,
188         } as Session;
189         const localSessions = this.getSessions().map(s => ({
190             ...s,
191             active: false,
192             status: SessionStatus.INVALIDATED
193         }));
194
195         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
196             const remoteHost = cfg.remoteHosts[clusterId];
197             return {
198                 clusterId,
199                 remoteHost,
200                 baseUrl: '',
201                 name: '',
202                 email: '',
203                 token: '',
204                 loggedIn: false,
205                 active: false,
206                 uuid: '',
207                 status: SessionStatus.INVALIDATED,
208                 apiRevision: 0,
209             } as Session;
210         });
211         const sessions = [currentSession]
212             .concat(cfgSessions)
213             .concat(localSessions)
214             .filter((r: Session) => r.clusterId !== "*");
215
216         const uniqSessions = uniqBy(sessions, 'clusterId');
217
218         return uniqSessions;
219     }
220 }