Merge branch '21128-toolbar-context-menu'
[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     can_write: boolean;
39     can_manage: boolean;
40 }
41
42 export class AuthService {
43
44     constructor(
45         protected apiClient: AxiosInstance,
46         protected baseUrl: string,
47         protected actions: ApiActions,
48         protected useSessionStorage: boolean = false) { }
49
50     private getStorage() {
51         if (this.useSessionStorage) {
52             return sessionStorage;
53         }
54         return localStorage;
55     }
56
57     public getStorageType() {
58         if (this.useSessionStorage) {
59             return SESSION_STORAGE;
60         }
61         return LOCAL_STORAGE;
62     }
63
64     public saveApiToken(token: string) {
65         this.removeApiToken();
66         this.getStorage().setItem(API_TOKEN_KEY, token);
67         const sp = token.split('/');
68         if (sp.length === 3) {
69             this.getStorage().setItem(HOME_CLUSTER, sp[1].substring(0, 5));
70         }
71     }
72
73     public setTargetUrl(url: string) {
74         localStorage.setItem(TARGET_URL, url);
75     }
76
77     public removeTargetURL() {
78         localStorage.removeItem(TARGET_URL);
79     }
80
81     public getTargetURL() {
82         return localStorage.getItem(TARGET_URL);
83     }
84
85     public removeApiToken() {
86         localStorage.removeItem(API_TOKEN_KEY);
87         sessionStorage.removeItem(API_TOKEN_KEY);
88     }
89
90     public getApiToken() {
91         return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
92     }
93
94     public getHomeCluster() {
95         return this.getStorage().getItem(HOME_CLUSTER) || undefined;
96     }
97
98     public getApiClient() {
99         return this.apiClient;
100     }
101
102     public removeUser() {
103         [localStorage, sessionStorage].forEach((storage) => {
104             storage.removeItem(USER_EMAIL_KEY);
105             storage.removeItem(USER_FIRST_NAME_KEY);
106             storage.removeItem(USER_LAST_NAME_KEY);
107             storage.removeItem(USER_UUID_KEY);
108             storage.removeItem(USER_OWNER_UUID_KEY);
109             storage.removeItem(USER_IS_ADMIN);
110             storage.removeItem(USER_IS_ACTIVE);
111             storage.removeItem(USER_USERNAME);
112             storage.removeItem(USER_PREFS);
113             storage.removeItem(TARGET_URL);
114         });
115     }
116
117     public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
118         const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
119         const homeClusterHost = remoteHosts[homeCluster];
120         const rd = new URL(window.location.href);
121         this.setTargetUrl(rd.pathname + rd.search);
122         window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
123     }
124
125     public logout(expireToken: string, preservePath: boolean) {
126         const fullUrl = new URL(window.location.href);
127         const wbBase = `${fullUrl.protocol}//${fullUrl.host}`;
128         const wbPath = fullUrl.pathname + fullUrl.search;
129         const returnTo = `${wbBase}${preservePath ? wbPath : ''}`
130
131         window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${returnTo}`);
132     }
133
134     public getUserDetails = (showErrors?: boolean): Promise<User> => {
135         const reqId = uuid();
136         this.actions.progressFn(reqId, true);
137         return this.apiClient
138             .get<UserDetailsResponse>('/users/current')
139             .then(resp => {
140                 this.actions.progressFn(reqId, false);
141                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
142                 return {
143                     email: resp.data.email,
144                     firstName: resp.data.first_name,
145                     lastName: resp.data.last_name,
146                     uuid: resp.data.uuid,
147                     ownerUuid: resp.data.owner_uuid,
148                     isAdmin: resp.data.is_admin,
149                     isActive: resp.data.is_active,
150                     username: resp.data.username,
151                     canWrite: resp.data.can_write,
152                     canManage: resp.data.can_manage,
153                     prefs
154                 };
155             })
156             .catch(e => {
157                 this.actions.progressFn(reqId, false);
158                 this.actions.errorFn(reqId, e, showErrors);
159                 throw e;
160             });
161     }
162
163     public getSessions(): Session[] {
164         try {
165             const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
166             return sessions;
167         } catch {
168             return [];
169         }
170     }
171
172     public saveSessions(sessions: Session[]) {
173         this.removeSessions();
174         this.getStorage().setItem("sessions", JSON.stringify(sessions));
175     }
176
177     public removeSessions() {
178         localStorage.removeItem("sessions");
179         sessionStorage.removeItem("sessions");
180     }
181
182     public buildSessions(cfg: Config, user?: User) {
183         const currentSession = {
184             clusterId: cfg.uuidPrefix,
185             remoteHost: cfg.rootUrl,
186             baseUrl: cfg.baseUrl,
187             name: user ? getUserDisplayName(user) : '',
188             email: user ? user.email : '',
189             userIsActive: user ? user.isActive : false,
190             token: this.getApiToken(),
191             loggedIn: true,
192             active: true,
193             uuid: user ? user.uuid : '',
194             status: SessionStatus.VALIDATED,
195             apiRevision: cfg.apiRevision,
196         } as Session;
197         const localSessions = this.getSessions().map(s => ({
198             ...s,
199             active: false,
200             status: SessionStatus.INVALIDATED
201         }));
202
203         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
204             const remoteHost = cfg.remoteHosts[clusterId];
205             return {
206                 clusterId,
207                 remoteHost,
208                 baseUrl: '',
209                 name: '',
210                 email: '',
211                 token: '',
212                 loggedIn: false,
213                 active: false,
214                 uuid: '',
215                 status: SessionStatus.INVALIDATED,
216                 apiRevision: 0,
217             } as Session;
218         });
219         const sessions = [currentSession]
220             .concat(cfgSessions)
221             .concat(localSessions)
222             .filter((r: Session) => r.clusterId !== "*");
223
224         const uniqSessions = uniqBy(sessions, 'clusterId');
225
226         return uniqSessions;
227     }
228 }