Add session validation
[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 } 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
21 export interface UserDetailsResponse {
22     email: string;
23     first_name: string;
24     last_name: string;
25     uuid: string;
26     owner_uuid: string;
27     is_admin: boolean;
28 }
29
30 export class AuthService {
31
32     constructor(
33         protected apiClient: AxiosInstance,
34         protected baseUrl: string,
35         protected actions: ApiActions) { }
36
37     public saveApiToken(token: string) {
38         localStorage.setItem(API_TOKEN_KEY, token);
39     }
40
41     public removeApiToken() {
42         localStorage.removeItem(API_TOKEN_KEY);
43     }
44
45     public getApiToken() {
46         return localStorage.getItem(API_TOKEN_KEY) || undefined;
47     }
48
49     public getUuid() {
50         return localStorage.getItem(USER_UUID_KEY) || undefined;
51     }
52
53     public getOwnerUuid() {
54         return localStorage.getItem(USER_OWNER_UUID_KEY) || undefined;
55     }
56
57     public getIsAdmin(): boolean {
58         return localStorage.getItem(USER_IS_ADMIN) === 'true';
59     }
60
61     public getUser(): User | undefined {
62         const email = localStorage.getItem(USER_EMAIL_KEY);
63         const firstName = localStorage.getItem(USER_FIRST_NAME_KEY);
64         const lastName = localStorage.getItem(USER_LAST_NAME_KEY);
65         const uuid = this.getUuid();
66         const ownerUuid = this.getOwnerUuid();
67         const isAdmin = this.getIsAdmin();
68
69         return email && firstName && lastName && uuid && ownerUuid
70             ? { email, firstName, lastName, uuid, ownerUuid, isAdmin }
71             : undefined;
72     }
73
74     public saveUser(user: User) {
75         localStorage.setItem(USER_EMAIL_KEY, user.email);
76         localStorage.setItem(USER_FIRST_NAME_KEY, user.firstName);
77         localStorage.setItem(USER_LAST_NAME_KEY, user.lastName);
78         localStorage.setItem(USER_UUID_KEY, user.uuid);
79         localStorage.setItem(USER_OWNER_UUID_KEY, user.ownerUuid);
80         localStorage.setItem(USER_IS_ADMIN, JSON.stringify(user.isAdmin));
81     }
82
83     public removeUser() {
84         localStorage.removeItem(USER_EMAIL_KEY);
85         localStorage.removeItem(USER_FIRST_NAME_KEY);
86         localStorage.removeItem(USER_LAST_NAME_KEY);
87         localStorage.removeItem(USER_UUID_KEY);
88         localStorage.removeItem(USER_OWNER_UUID_KEY);
89         localStorage.removeItem(USER_IS_ADMIN);
90     }
91
92     public login() {
93         const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
94         window.location.assign(`${this.baseUrl || ""}/login?return_to=${currentUrl}`);
95     }
96
97     public logout() {
98         const currentUrl = `${window.location.protocol}//${window.location.host}`;
99         window.location.assign(`${this.baseUrl || ""}/logout?return_to=${currentUrl}`);
100     }
101
102     public getUserDetails = (): Promise<User> => {
103         const reqId = uuid();
104         this.actions.progressFn(reqId, true);
105         return this.apiClient
106             .get<UserDetailsResponse>('/users/current')
107             .then(resp => {
108                 this.actions.progressFn(reqId, false);
109                 return {
110                     email: resp.data.email,
111                     firstName: resp.data.first_name,
112                     lastName: resp.data.last_name,
113                     uuid: resp.data.uuid,
114                     ownerUuid: resp.data.owner_uuid,
115                     isAdmin: resp.data.is_admin
116                 };
117             })
118             .catch(e => {
119                 this.actions.progressFn(reqId, false);
120                 this.actions.errorFn(reqId, e);
121                 throw e;
122             });
123     }
124
125     public getRootUuid() {
126         const uuid = this.getOwnerUuid();
127         const uuidParts = uuid ? uuid.split('-') : [];
128         return uuidParts.length > 1 ? `${uuidParts[0]}-${uuidParts[1]}` : undefined;
129     }
130
131     public getSessions(): Session[] {
132         try {
133             const sessions = JSON.parse(localStorage.getItem("sessions") || '');
134             return sessions;
135         } catch {
136             return [];
137         }
138     }
139
140     public saveSessions(sessions: Session[]) {
141         localStorage.setItem("sessions", JSON.stringify(sessions));
142     }
143
144     public buildSessions(cfg: Config, user?: User) {
145         const currentSession = {
146             clusterId: cfg.uuidPrefix,
147             remoteHost: cfg.rootUrl,
148             baseUrl: cfg.baseUrl,
149             username: getUserFullname(user),
150             email: user ? user.email : '',
151             token: this.getApiToken(),
152             loggedIn: true,
153             active: true,
154             status: SessionStatus.VALIDATED
155         } as Session;
156         const localSessions = this.getSessions();
157         const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
158             const remoteHost = cfg.remoteHosts[clusterId];
159             return {
160                 clusterId,
161                 remoteHost,
162                 baseUrl: '',
163                 username: '',
164                 email: '',
165                 token: '',
166                 loggedIn: false,
167                 active: false,
168                 status: SessionStatus.INVALIDATED
169             } as Session;
170         });
171         const sessions = [currentSession]
172             .concat(localSessions)
173             .concat(cfgSessions);
174
175         const uniqSessions = uniqBy(sessions, 'clusterId');
176
177         return uniqSessions;
178     }
179 }