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