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