1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { User, UserPrefs, getUserDisplayName } from 'models/user';
6 import { AxiosInstance } from "axios";
7 import { ApiActions } from "services/api/api-actions";
8 import uuid from "uuid/v4";
9 import { Session, SessionStatus } from "models/session";
10 import { Config } from "common/config";
11 import { uniqBy } from "lodash";
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 export const LOCAL_STORAGE = 'localStorage';
26 export const SESSION_STORAGE = 'sessionStorage';
28 export interface UserDetailsResponse {
42 export class AuthService {
45 protected apiClient: AxiosInstance,
46 protected baseUrl: string,
47 protected actions: ApiActions,
48 protected useSessionStorage: boolean = false) { }
50 private getStorage() {
51 if (this.useSessionStorage) {
52 return sessionStorage;
57 public getStorageType() {
58 if (this.useSessionStorage) {
59 return SESSION_STORAGE;
64 public saveApiToken(token: string) {
65 this.removeApiToken();
66 this.getStorage().setItem(API_TOKEN_KEY, token);
67 const sp = token.split('/');
68 if (sp.length === 3) {
69 this.getStorage().setItem(HOME_CLUSTER, sp[1].substring(0, 5));
73 public setTargetUrl(url: string) {
74 localStorage.setItem(TARGET_URL, url);
77 public removeTargetURL() {
78 localStorage.removeItem(TARGET_URL);
81 public getTargetURL() {
82 return localStorage.getItem(TARGET_URL);
85 public removeApiToken() {
86 localStorage.removeItem(API_TOKEN_KEY);
87 sessionStorage.removeItem(API_TOKEN_KEY);
90 public getApiToken() {
91 return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
94 public getHomeCluster() {
95 return this.getStorage().getItem(HOME_CLUSTER) || undefined;
98 public getApiClient() {
99 return this.apiClient;
102 public removeUser() {
103 [localStorage, sessionStorage].forEach((storage) => {
104 storage.removeItem(USER_EMAIL_KEY);
105 storage.removeItem(USER_FIRST_NAME_KEY);
106 storage.removeItem(USER_LAST_NAME_KEY);
107 storage.removeItem(USER_UUID_KEY);
108 storage.removeItem(USER_OWNER_UUID_KEY);
109 storage.removeItem(USER_IS_ADMIN);
110 storage.removeItem(USER_IS_ACTIVE);
111 storage.removeItem(USER_USERNAME);
112 storage.removeItem(USER_PREFS);
113 storage.removeItem(TARGET_URL);
117 public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
118 const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
119 const homeClusterHost = remoteHosts[homeCluster];
120 const rd = new URL(window.location.href);
121 this.setTargetUrl(rd.pathname + rd.search);
122 window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
125 public logout(expireToken: string, preservePath: boolean) {
126 const fullUrl = new URL(window.location.href);
127 const wbBase = `${fullUrl.protocol}//${fullUrl.host}`;
128 const wbPath = fullUrl.pathname + fullUrl.search;
129 const returnTo = `${wbBase}${preservePath ? wbPath : ''}`
131 window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${returnTo}`);
134 public getUserDetails = (showErrors?: boolean): Promise<User> => {
135 const reqId = uuid();
136 this.actions.progressFn(reqId, true);
137 return this.apiClient
138 .get<UserDetailsResponse>('/users/current')
140 this.actions.progressFn(reqId, false);
141 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
143 email: resp.data.email,
144 firstName: resp.data.first_name,
145 lastName: resp.data.last_name,
146 uuid: resp.data.uuid,
147 ownerUuid: resp.data.owner_uuid,
148 isAdmin: resp.data.is_admin,
149 isActive: resp.data.is_active,
150 username: resp.data.username,
151 canWrite: resp.data.can_write,
152 canManage: resp.data.can_manage,
157 this.actions.progressFn(reqId, false);
158 this.actions.errorFn(reqId, e, showErrors);
163 public getSessions(): Session[] {
165 const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
172 public saveSessions(sessions: Session[]) {
173 this.removeSessions();
174 this.getStorage().setItem("sessions", JSON.stringify(sessions));
177 public removeSessions() {
178 localStorage.removeItem("sessions");
179 sessionStorage.removeItem("sessions");
182 public buildSessions(cfg: Config, user?: User) {
183 const currentSession = {
184 clusterId: cfg.uuidPrefix,
185 remoteHost: cfg.rootUrl,
186 baseUrl: cfg.baseUrl,
187 name: user ? getUserDisplayName(user) : '',
188 email: user ? user.email : '',
189 userIsActive: user ? user.isActive : false,
190 token: this.getApiToken(),
193 uuid: user ? user.uuid : '',
194 status: SessionStatus.VALIDATED,
195 apiRevision: cfg.apiRevision,
197 const localSessions = this.getSessions().map(s => ({
200 status: SessionStatus.INVALIDATED
203 const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
204 const remoteHost = cfg.remoteHosts[clusterId];
215 status: SessionStatus.INVALIDATED,
219 const sessions = [currentSession]
221 .concat(localSessions)
222 .filter((r: Session) => r.clusterId !== "*");
224 const uniqSessions = uniqBy(sessions, 'clusterId');