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