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