16941: Fix AxiosInstance import. Add apiClient accessor
[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 { User, UserPrefs, getUserDisplayName } 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         protected useSessionStorage: boolean = false) { }
44
45     private getStorage() {
46         if (this.useSessionStorage) {
47             return sessionStorage;
48         }
49         return localStorage;
50     }
51
52     public saveApiToken(token: string) {
53         this.getStorage().setItem(API_TOKEN_KEY, token);
54         const sp = token.split('/');
55         if (sp.length === 3) {
56             this.getStorage().setItem(HOME_CLUSTER, sp[1].substr(0, 5));
57         }
58     }
59
60     public removeApiToken() {
61         this.getStorage().removeItem(API_TOKEN_KEY);
62     }
63
64     public getApiToken() {
65         return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
66     }
67
68     public getHomeCluster() {
69         return this.getStorage().getItem(HOME_CLUSTER) || undefined;
70     }
71
72     public getApiClient() {
73         return this.apiClient;
74     }
75
76     public removeUser() {
77         this.getStorage().removeItem(USER_EMAIL_KEY);
78         this.getStorage().removeItem(USER_FIRST_NAME_KEY);
79         this.getStorage().removeItem(USER_LAST_NAME_KEY);
80         this.getStorage().removeItem(USER_UUID_KEY);
81         this.getStorage().removeItem(USER_OWNER_UUID_KEY);
82         this.getStorage().removeItem(USER_IS_ADMIN);
83         this.getStorage().removeItem(USER_IS_ACTIVE);
84         this.getStorage().removeItem(USER_USERNAME);
85         this.getStorage().removeItem(USER_PREFS);
86     }
87
88     public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
89         const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
90         const homeClusterHost = remoteHosts[homeCluster];
91         window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
92     }
93
94     public logout() {
95         const currentUrl = `${window.location.protocol}//${window.location.host}`;
96         window.location.assign(`${this.baseUrl || ""}/logout?return_to=${currentUrl}`);
97     }
98
99     public getUserDetails = (): Promise<User> => {
100         const reqId = uuid();
101         this.actions.progressFn(reqId, true);
102         return this.apiClient
103             .get<UserDetailsResponse>('/users/current')
104             .then(resp => {
105                 this.actions.progressFn(reqId, false);
106                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
107                 return {
108                     email: resp.data.email,
109                     firstName: resp.data.first_name,
110                     lastName: resp.data.last_name,
111                     uuid: resp.data.uuid,
112                     ownerUuid: resp.data.owner_uuid,
113                     isAdmin: resp.data.is_admin,
114                     isActive: resp.data.is_active,
115                     username: resp.data.username,
116                     prefs
117                 };
118             })
119             .catch(e => {
120                 this.actions.progressFn(reqId, false);
121                 this.actions.errorFn(reqId, e);
122                 throw e;
123             });
124     }
125
126     public getSessions(): Session[] {
127         try {
128             const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
129             return sessions;
130         } catch {
131             return [];
132         }
133     }
134
135     public saveSessions(sessions: Session[]) {
136         this.getStorage().setItem("sessions", JSON.stringify(sessions));
137     }
138
139     public removeSessions() {
140         this.getStorage().removeItem("sessions");
141     }
142
143     public buildSessions(cfg: Config, user?: User) {
144         const currentSession = {
145             clusterId: cfg.uuidPrefix,
146             remoteHost: cfg.rootUrl,
147             baseUrl: cfg.baseUrl,
148             name: user ? getUserDisplayName(user) : '',
149             email: user ? user.email : '',
150             userIsActive: user ? user.isActive : false,
151             token: this.getApiToken(),
152             loggedIn: true,
153             active: true,
154             uuid: user ? user.uuid : '',
155             status: SessionStatus.VALIDATED,
156             apiRevision: cfg.apiRevision,
157         } as Session;
158         const localSessions = this.getSessions().map(s => ({
159             ...s,
160             active: false,
161             status: SessionStatus.INVALIDATED
162         }));
163
164         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
165             const remoteHost = cfg.remoteHosts[clusterId];
166             return {
167                 clusterId,
168                 remoteHost,
169                 baseUrl: '',
170                 name: '',
171                 email: '',
172                 token: '',
173                 loggedIn: false,
174                 active: false,
175                 uuid: '',
176                 status: SessionStatus.INVALIDATED,
177                 apiRevision: 0,
178             } as Session;
179         });
180         const sessions = [currentSession]
181             .concat(cfgSessions)
182             .concat(localSessions)
183             .filter((r: Session) => r.clusterId !== "*");
184
185         const uniqSessions = uniqBy(sessions, 'clusterId');
186
187         return uniqSessions;
188     }
189 }