17101: Persisting url before the login process
[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 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         this.getStorage().setItem(TARGET_URL, window.location.href);
102         window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
103     }
104
105     public logout() {
106         const currentUrl = `${window.location.protocol}//${window.location.host}`;
107         window.location.assign(`${this.baseUrl || ""}/logout?return_to=${currentUrl}`);
108     }
109
110     public getUserDetails = (showErrors?: boolean): Promise<User> => {
111         const reqId = uuid();
112         this.actions.progressFn(reqId, true);
113         return this.apiClient
114             .get<UserDetailsResponse>('/users/current')
115             .then(resp => {
116                 this.actions.progressFn(reqId, false);
117                 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
118                 return {
119                     email: resp.data.email,
120                     firstName: resp.data.first_name,
121                     lastName: resp.data.last_name,
122                     uuid: resp.data.uuid,
123                     ownerUuid: resp.data.owner_uuid,
124                     isAdmin: resp.data.is_admin,
125                     isActive: resp.data.is_active,
126                     username: resp.data.username,
127                     prefs
128                 };
129             })
130             .catch(e => {
131                 this.actions.progressFn(reqId, false);
132                 this.actions.errorFn(reqId, e, showErrors);
133                 throw e;
134             });
135     }
136
137     public getSessions(): Session[] {
138         try {
139             const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
140             return sessions;
141         } catch {
142             return [];
143         }
144     }
145
146     public saveSessions(sessions: Session[]) {
147         this.getStorage().setItem("sessions", JSON.stringify(sessions));
148     }
149
150     public removeSessions() {
151         this.getStorage().removeItem("sessions");
152     }
153
154     public buildSessions(cfg: Config, user?: User) {
155         const currentSession = {
156             clusterId: cfg.uuidPrefix,
157             remoteHost: cfg.rootUrl,
158             baseUrl: cfg.baseUrl,
159             name: user ? getUserDisplayName(user) : '',
160             email: user ? user.email : '',
161             userIsActive: user ? user.isActive : false,
162             token: this.getApiToken(),
163             loggedIn: true,
164             active: true,
165             uuid: user ? user.uuid : '',
166             status: SessionStatus.VALIDATED,
167             apiRevision: cfg.apiRevision,
168         } as Session;
169         const localSessions = this.getSessions().map(s => ({
170             ...s,
171             active: false,
172             status: SessionStatus.INVALIDATED
173         }));
174
175         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
176             const remoteHost = cfg.remoteHosts[clusterId];
177             return {
178                 clusterId,
179                 remoteHost,
180                 baseUrl: '',
181                 name: '',
182                 email: '',
183                 token: '',
184                 loggedIn: false,
185                 active: false,
186                 uuid: '',
187                 status: SessionStatus.INVALIDATED,
188                 apiRevision: 0,
189             } as Session;
190         });
191         const sessions = [currentSession]
192             .concat(cfgSessions)
193             .concat(localSessions)
194             .filter((r: Session) => r.clusterId !== "*");
195
196         const uniqSessions = uniqBy(sessions, 'clusterId');
197
198         return uniqSessions;
199     }
200 }