16947: Don't show misleading session validate errors.
[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 removeUser() {
73         this.getStorage().removeItem(USER_EMAIL_KEY);
74         this.getStorage().removeItem(USER_FIRST_NAME_KEY);
75         this.getStorage().removeItem(USER_LAST_NAME_KEY);
76         this.getStorage().removeItem(USER_UUID_KEY);
77         this.getStorage().removeItem(USER_OWNER_UUID_KEY);
78         this.getStorage().removeItem(USER_IS_ADMIN);
79         this.getStorage().removeItem(USER_IS_ACTIVE);
80         this.getStorage().removeItem(USER_USERNAME);
81         this.getStorage().removeItem(USER_PREFS);
82     }
83
84     public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
85         const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
86         const homeClusterHost = remoteHosts[homeCluster];
87         window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
88     }
89
90     public logout() {
91         const currentUrl = `${window.location.protocol}//${window.location.host}`;
92         window.location.assign(`${this.baseUrl || ""}/logout?return_to=${currentUrl}`);
93     }
94
95     public getUserDetails = (showErrors?: boolean): Promise<User> => {
96         const reqId = uuid();
97         this.actions.progressFn(reqId, true);
98         return this.apiClient
99             .get<UserDetailsResponse>('/users/current')
100             .then(resp => {
101                 this.actions.progressFn(reqId, false);
102                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
103                 return {
104                     email: resp.data.email,
105                     firstName: resp.data.first_name,
106                     lastName: resp.data.last_name,
107                     uuid: resp.data.uuid,
108                     ownerUuid: resp.data.owner_uuid,
109                     isAdmin: resp.data.is_admin,
110                     isActive: resp.data.is_active,
111                     username: resp.data.username,
112                     prefs
113                 };
114             })
115             .catch(e => {
116                 this.actions.progressFn(reqId, false);
117                 this.actions.errorFn(reqId, e, showErrors);
118                 throw e;
119             });
120     }
121
122     public getSessions(): Session[] {
123         try {
124             const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
125             return sessions;
126         } catch {
127             return [];
128         }
129     }
130
131     public saveSessions(sessions: Session[]) {
132         this.getStorage().setItem("sessions", JSON.stringify(sessions));
133     }
134
135     public removeSessions() {
136         this.getStorage().removeItem("sessions");
137     }
138
139     public buildSessions(cfg: Config, user?: User) {
140         const currentSession = {
141             clusterId: cfg.uuidPrefix,
142             remoteHost: cfg.rootUrl,
143             baseUrl: cfg.baseUrl,
144             name: user ? getUserDisplayName(user): '',
145             email: user ? user.email : '',
146             token: this.getApiToken(),
147             loggedIn: true,
148             active: true,
149             uuid: user ? user.uuid : '',
150             status: SessionStatus.VALIDATED,
151             apiRevision: cfg.apiRevision,
152         } as Session;
153         const localSessions = this.getSessions().map(s => ({
154             ...s,
155             active: false,
156             status: SessionStatus.INVALIDATED
157         }));
158
159         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
160             const remoteHost = cfg.remoteHosts[clusterId];
161             return {
162                 clusterId,
163                 remoteHost,
164                 baseUrl: '',
165                 name: '',
166                 email: '',
167                 token: '',
168                 loggedIn: false,
169                 active: false,
170                 uuid: '',
171                 status: SessionStatus.INVALIDATED,
172                 apiRevision: 0,
173             } as Session;
174         });
175         const sessions = [currentSession]
176             .concat(cfgSessions)
177             .concat(localSessions)
178             .filter((r: Session) => r.clusterId !== "*");
179
180         const uniqSessions = uniqBy(sessions, 'clusterId');
181
182         return uniqSessions;
183     }
184 }