Merge branch 'master' of git.curoverse.com:arvados-workbench2 into 14248_assigning_pr...
[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 { getUserFullname, User, UserPrefs } 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 API_TOKEN_KEY = 'apiToken';
14 export const USER_EMAIL_KEY = 'userEmail';
15 export const USER_FIRST_NAME_KEY = 'userFirstName';
16 export const USER_LAST_NAME_KEY = 'userLastName';
17 export const USER_UUID_KEY = 'userUuid';
18 export const USER_OWNER_UUID_KEY = 'userOwnerUuid';
19 export const USER_IS_ADMIN = 'isAdmin';
20 export const USER_IDENTITY_URL = 'identityUrl';
21 export const USER_PREFS = 'prefs';
22
23 export interface UserDetailsResponse {
24     email: string;
25     first_name: string;
26     last_name: string;
27     uuid: string;
28     owner_uuid: string;
29     is_admin: boolean;
30     identity_url: string;
31     prefs: UserPrefs;
32 }
33
34 export class AuthService {
35
36     constructor(
37         protected apiClient: AxiosInstance,
38         protected baseUrl: string,
39         protected actions: ApiActions) { }
40
41     public saveApiToken(token: string) {
42         localStorage.setItem(API_TOKEN_KEY, token);
43     }
44
45     public removeApiToken() {
46         localStorage.removeItem(API_TOKEN_KEY);
47     }
48
49     public getApiToken() {
50         return localStorage.getItem(API_TOKEN_KEY) || undefined;
51     }
52
53     public getUuid() {
54         return localStorage.getItem(USER_UUID_KEY) || undefined;
55     }
56
57     public getOwnerUuid() {
58         return localStorage.getItem(USER_OWNER_UUID_KEY) || undefined;
59     }
60
61     public getIsAdmin(): boolean {
62         return localStorage.getItem(USER_IS_ADMIN) === 'true';
63     }
64
65     public getUser(): User | undefined {
66         const email = localStorage.getItem(USER_EMAIL_KEY);
67         const firstName = localStorage.getItem(USER_FIRST_NAME_KEY);
68         const lastName = localStorage.getItem(USER_LAST_NAME_KEY);
69         const uuid = this.getUuid();
70         const ownerUuid = this.getOwnerUuid();
71         const isAdmin = this.getIsAdmin();
72         const identityUrl = localStorage.getItem(USER_IDENTITY_URL);
73         const prefs = JSON.parse(localStorage.getItem(USER_PREFS) || '{"profile": {}}');
74
75         return email && firstName && lastName && uuid && ownerUuid && identityUrl && prefs
76             ? { email, firstName, lastName, uuid, ownerUuid, isAdmin, identityUrl, prefs }
77             : undefined;
78     }
79
80     public saveUser(user: User) {
81         localStorage.setItem(USER_EMAIL_KEY, user.email);
82         localStorage.setItem(USER_FIRST_NAME_KEY, user.firstName);
83         localStorage.setItem(USER_LAST_NAME_KEY, user.lastName);
84         localStorage.setItem(USER_UUID_KEY, user.uuid);
85         localStorage.setItem(USER_OWNER_UUID_KEY, user.ownerUuid);
86         localStorage.setItem(USER_IS_ADMIN, JSON.stringify(user.isAdmin));
87         localStorage.setItem(USER_IDENTITY_URL, user.identityUrl);
88         localStorage.setItem(USER_PREFS, JSON.stringify(user.prefs));
89     }
90
91     public removeUser() {
92         localStorage.removeItem(USER_EMAIL_KEY);
93         localStorage.removeItem(USER_FIRST_NAME_KEY);
94         localStorage.removeItem(USER_LAST_NAME_KEY);
95         localStorage.removeItem(USER_UUID_KEY);
96         localStorage.removeItem(USER_OWNER_UUID_KEY);
97         localStorage.removeItem(USER_IS_ADMIN);
98         localStorage.removeItem(USER_IDENTITY_URL);
99         localStorage.removeItem(USER_PREFS);
100     }
101
102     public login() {
103         const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
104         window.location.assign(`${this.baseUrl || ""}/login?return_to=${currentUrl}`);
105     }
106
107     public logout() {
108         const currentUrl = `${window.location.protocol}//${window.location.host}`;
109         window.location.assign(`${this.baseUrl || ""}/logout?return_to=${currentUrl}`);
110     }
111
112     public getUserDetails = (): Promise<User> => {
113         const reqId = uuid();
114         this.actions.progressFn(reqId, true);
115         return this.apiClient
116             .get<UserDetailsResponse>('/users/current')
117             .then(resp => {
118                 this.actions.progressFn(reqId, false);
119                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {}};
120                 return {
121                     email: resp.data.email,
122                     firstName: resp.data.first_name,
123                     lastName: resp.data.last_name,
124                     uuid: resp.data.uuid,
125                     ownerUuid: resp.data.owner_uuid,
126                     isAdmin: resp.data.is_admin,
127                     identityUrl: resp.data.identity_url,
128                     prefs
129                 };
130             })
131             .catch(e => {
132                 this.actions.progressFn(reqId, false);
133                 this.actions.errorFn(reqId, e);
134                 throw e;
135             });
136     }
137
138     public getRootUuid() {
139         const uuid = this.getOwnerUuid();
140         const uuidParts = uuid ? uuid.split('-') : [];
141         return uuidParts.length > 1 ? `${uuidParts[0]}-${uuidParts[1]}` : undefined;
142     }
143
144     public getSessions(): Session[] {
145         try {
146             const sessions = JSON.parse(localStorage.getItem("sessions") || '');
147             return sessions;
148         } catch {
149             return [];
150         }
151     }
152
153     public saveSessions(sessions: Session[]) {
154         localStorage.setItem("sessions", JSON.stringify(sessions));
155     }
156
157     public buildSessions(cfg: Config, user?: User) {
158         const currentSession = {
159             clusterId: cfg.uuidPrefix,
160             remoteHost: cfg.rootUrl,
161             baseUrl: cfg.baseUrl,
162             username: getUserFullname(user),
163             email: user ? user.email : '',
164             token: this.getApiToken(),
165             loggedIn: true,
166             active: true,
167             status: SessionStatus.VALIDATED
168         } as Session;
169         const localSessions = this.getSessions();
170         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
171             const remoteHost = cfg.remoteHosts[clusterId];
172             return {
173                 clusterId,
174                 remoteHost,
175                 baseUrl: '',
176                 username: '',
177                 email: '',
178                 token: '',
179                 loggedIn: false,
180                 active: false,
181                 status: SessionStatus.INVALIDATED
182             } as Session;
183         });
184         const sessions = [currentSession]
185             .concat(localSessions)
186             .concat(cfgSessions);
187
188         const uniqSessions = uniqBy(sessions, 'clusterId');
189
190         return uniqSessions;
191     }
192 }