18284: Add shell login command copy button and style webshell button like a button.
[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].substr(0, 5));
68         }
69     }
70
71     public removeTargetURL() {
72         localStorage.removeItem(TARGET_URL);
73         sessionStorage.removeItem(TARGET_URL);
74     }
75
76     public getTargetURL() {
77         return this.getStorage().getItem(TARGET_URL);
78     }
79
80     public removeApiToken() {
81         localStorage.removeItem(API_TOKEN_KEY);
82         sessionStorage.removeItem(API_TOKEN_KEY);
83     }
84
85     public getApiToken() {
86         return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
87     }
88
89     public getHomeCluster() {
90         return this.getStorage().getItem(HOME_CLUSTER) || undefined;
91     }
92
93     public getApiClient() {
94         return this.apiClient;
95     }
96
97     public removeUser() {
98         [localStorage, sessionStorage].forEach((storage) => {
99             storage.removeItem(USER_EMAIL_KEY);
100             storage.removeItem(USER_FIRST_NAME_KEY);
101             storage.removeItem(USER_LAST_NAME_KEY);
102             storage.removeItem(USER_UUID_KEY);
103             storage.removeItem(USER_OWNER_UUID_KEY);
104             storage.removeItem(USER_IS_ADMIN);
105             storage.removeItem(USER_IS_ACTIVE);
106             storage.removeItem(USER_USERNAME);
107             storage.removeItem(USER_PREFS);
108             storage.removeItem(TARGET_URL);
109         });
110     }
111
112     public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
113         const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
114         const homeClusterHost = remoteHosts[homeCluster];
115         const rd = new URL(window.location.href);
116         this.getStorage().setItem(TARGET_URL, rd.pathname + rd.search);
117         window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
118     }
119
120     public logout(expireToken: string) {
121         const currentUrl = `${window.location.protocol}//${window.location.host}`;
122         window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${currentUrl}`);
123     }
124
125     public getUserDetails = (showErrors?: boolean): Promise<User> => {
126         const reqId = uuid();
127         this.actions.progressFn(reqId, true);
128         return this.apiClient
129             .get<UserDetailsResponse>('/users/current')
130             .then(resp => {
131                 this.actions.progressFn(reqId, false);
132                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
133                 return {
134                     email: resp.data.email,
135                     firstName: resp.data.first_name,
136                     lastName: resp.data.last_name,
137                     uuid: resp.data.uuid,
138                     ownerUuid: resp.data.owner_uuid,
139                     isAdmin: resp.data.is_admin,
140                     isActive: resp.data.is_active,
141                     username: resp.data.username,
142                     prefs
143                 };
144             })
145             .catch(e => {
146                 this.actions.progressFn(reqId, false);
147                 this.actions.errorFn(reqId, e, showErrors);
148                 throw e;
149             });
150     }
151
152     public getSessions(): Session[] {
153         try {
154             const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
155             return sessions;
156         } catch {
157             return [];
158         }
159     }
160
161     public saveSessions(sessions: Session[]) {
162         this.removeSessions();
163         this.getStorage().setItem("sessions", JSON.stringify(sessions));
164     }
165
166     public removeSessions() {
167         localStorage.removeItem("sessions");
168         sessionStorage.removeItem("sessions");
169     }
170
171     public buildSessions(cfg: Config, user?: User) {
172         const currentSession = {
173             clusterId: cfg.uuidPrefix,
174             remoteHost: cfg.rootUrl,
175             baseUrl: cfg.baseUrl,
176             name: user ? getUserDisplayName(user) : '',
177             email: user ? user.email : '',
178             userIsActive: user ? user.isActive : false,
179             token: this.getApiToken(),
180             loggedIn: true,
181             active: true,
182             uuid: user ? user.uuid : '',
183             status: SessionStatus.VALIDATED,
184             apiRevision: cfg.apiRevision,
185         } as Session;
186         const localSessions = this.getSessions().map(s => ({
187             ...s,
188             active: false,
189             status: SessionStatus.INVALIDATED
190         }));
191
192         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
193             const remoteHost = cfg.remoteHosts[clusterId];
194             return {
195                 clusterId,
196                 remoteHost,
197                 baseUrl: '',
198                 name: '',
199                 email: '',
200                 token: '',
201                 loggedIn: false,
202                 active: false,
203                 uuid: '',
204                 status: SessionStatus.INVALIDATED,
205                 apiRevision: 0,
206             } as Session;
207         });
208         const sessions = [currentSession]
209             .concat(cfgSessions)
210             .concat(localSessions)
211             .filter((r: Session) => r.clusterId !== "*");
212
213         const uniqSessions = uniqBy(sessions, 'clusterId');
214
215         return uniqSessions;
216     }
217 }