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 {
40 export class AuthService {
43 protected apiClient: AxiosInstance,
44 protected baseUrl: string,
45 protected actions: ApiActions,
46 protected useSessionStorage: boolean = false) { }
48 private getStorage() {
49 if (this.useSessionStorage) {
50 return sessionStorage;
55 public getStorageType() {
56 if (this.useSessionStorage) {
57 return SESSION_STORAGE;
62 public saveApiToken(token: string) {
63 this.removeApiToken();
64 this.getStorage().setItem(API_TOKEN_KEY, token);
65 const sp = token.split('/');
66 if (sp.length === 3) {
67 this.getStorage().setItem(HOME_CLUSTER, sp[1].substring(0, 5));
71 public removeTargetURL() {
72 localStorage.removeItem(TARGET_URL);
73 sessionStorage.removeItem(TARGET_URL);
76 public getTargetURL() {
77 return this.getStorage().getItem(TARGET_URL);
80 public removeApiToken() {
81 localStorage.removeItem(API_TOKEN_KEY);
82 sessionStorage.removeItem(API_TOKEN_KEY);
85 public getApiToken() {
86 return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
89 public getHomeCluster() {
90 return this.getStorage().getItem(HOME_CLUSTER) || undefined;
93 public getApiClient() {
94 return this.apiClient;
98 [localStorage, sessionStorage].forEach((storage) => {
99 storage.removeItem(USER_EMAIL_KEY);
100 storage.removeItem(USER_FIRST_NAME_KEY);
101 storage.removeItem(USER_LAST_NAME_KEY);
102 storage.removeItem(USER_UUID_KEY);
103 storage.removeItem(USER_OWNER_UUID_KEY);
104 storage.removeItem(USER_IS_ADMIN);
105 storage.removeItem(USER_IS_ACTIVE);
106 storage.removeItem(USER_USERNAME);
107 storage.removeItem(USER_PREFS);
108 storage.removeItem(TARGET_URL);
112 public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
113 const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
114 const homeClusterHost = remoteHosts[homeCluster];
115 const rd = new URL(window.location.href);
116 this.getStorage().setItem(TARGET_URL, rd.pathname + rd.search);
117 window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
120 public logout(expireToken: string) {
121 const currentUrl = `${window.location.protocol}//${window.location.host}`;
122 window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${currentUrl}`);
125 public getUserDetails = (showErrors?: boolean): Promise<User> => {
126 const reqId = uuid();
127 this.actions.progressFn(reqId, true);
128 return this.apiClient
129 .get<UserDetailsResponse>('/users/current')
131 this.actions.progressFn(reqId, false);
132 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
134 email: resp.data.email,
135 firstName: resp.data.first_name,
136 lastName: resp.data.last_name,
137 uuid: resp.data.uuid,
138 ownerUuid: resp.data.owner_uuid,
139 isAdmin: resp.data.is_admin,
140 isActive: resp.data.is_active,
141 username: resp.data.username,
146 this.actions.progressFn(reqId, false);
147 this.actions.errorFn(reqId, e, showErrors);
152 public getSessions(): Session[] {
154 const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
161 public saveSessions(sessions: Session[]) {
162 this.removeSessions();
163 this.getStorage().setItem("sessions", JSON.stringify(sessions));
166 public removeSessions() {
167 localStorage.removeItem("sessions");
168 sessionStorage.removeItem("sessions");
171 public buildSessions(cfg: Config, user?: User) {
172 const currentSession = {
173 clusterId: cfg.uuidPrefix,
174 remoteHost: cfg.rootUrl,
175 baseUrl: cfg.baseUrl,
176 name: user ? getUserDisplayName(user) : '',
177 email: user ? user.email : '',
178 userIsActive: user ? user.isActive : false,
179 token: this.getApiToken(),
182 uuid: user ? user.uuid : '',
183 status: SessionStatus.VALIDATED,
184 apiRevision: cfg.apiRevision,
186 const localSessions = this.getSessions().map(s => ({
189 status: SessionStatus.INVALIDATED
192 const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
193 const remoteHost = cfg.remoteHosts[clusterId];
204 status: SessionStatus.INVALIDATED,
208 const sessions = [currentSession]
210 .concat(localSessions)
211 .filter((r: Session) => r.clusterId !== "*");
213 const uniqSessions = uniqBy(sessions, 'clusterId');