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