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