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 setTargetUrl(url: string) {
72 localStorage.setItem(TARGET_URL, url);
75 public removeTargetURL() {
76 localStorage.removeItem(TARGET_URL);
79 public getTargetURL() {
80 return localStorage.getItem(TARGET_URL);
83 public removeApiToken() {
84 localStorage.removeItem(API_TOKEN_KEY);
85 sessionStorage.removeItem(API_TOKEN_KEY);
88 public getApiToken() {
89 return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
92 public getHomeCluster() {
93 return this.getStorage().getItem(HOME_CLUSTER) || undefined;
96 public getApiClient() {
97 return this.apiClient;
100 public removeUser() {
101 [localStorage, sessionStorage].forEach((storage) => {
102 storage.removeItem(USER_EMAIL_KEY);
103 storage.removeItem(USER_FIRST_NAME_KEY);
104 storage.removeItem(USER_LAST_NAME_KEY);
105 storage.removeItem(USER_UUID_KEY);
106 storage.removeItem(USER_OWNER_UUID_KEY);
107 storage.removeItem(USER_IS_ADMIN);
108 storage.removeItem(USER_IS_ACTIVE);
109 storage.removeItem(USER_USERNAME);
110 storage.removeItem(USER_PREFS);
111 storage.removeItem(TARGET_URL);
115 public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
116 const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
117 const homeClusterHost = remoteHosts[homeCluster];
118 const rd = new URL(window.location.href);
119 this.setTargetUrl(rd.pathname + rd.search);
120 window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
123 public logout(expireToken: string, preservePath: boolean) {
124 const fullUrl = new URL(window.location.href);
125 const wbBase = `${fullUrl.protocol}//${fullUrl.host}`;
126 const wbPath = fullUrl.pathname + fullUrl.search;
127 const returnTo = `${wbBase}${preservePath ? wbPath : ''}`
129 window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${returnTo}`);
132 public getUserDetails = (showErrors?: boolean): Promise<User> => {
133 const reqId = uuid();
134 this.actions.progressFn(reqId, true);
135 return this.apiClient
136 .get<UserDetailsResponse>('/users/current')
138 this.actions.progressFn(reqId, false);
139 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
141 email: resp.data.email,
142 firstName: resp.data.first_name,
143 lastName: resp.data.last_name,
144 uuid: resp.data.uuid,
145 ownerUuid: resp.data.owner_uuid,
146 isAdmin: resp.data.is_admin,
147 isActive: resp.data.is_active,
148 username: resp.data.username,
153 this.actions.progressFn(reqId, false);
154 this.actions.errorFn(reqId, e, showErrors);
159 public getSessions(): Session[] {
161 const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
168 public saveSessions(sessions: Session[]) {
169 this.removeSessions();
170 this.getStorage().setItem("sessions", JSON.stringify(sessions));
173 public removeSessions() {
174 localStorage.removeItem("sessions");
175 sessionStorage.removeItem("sessions");
178 public buildSessions(cfg: Config, user?: User) {
179 const currentSession = {
180 clusterId: cfg.uuidPrefix,
181 remoteHost: cfg.rootUrl,
182 baseUrl: cfg.baseUrl,
183 name: user ? getUserDisplayName(user) : '',
184 email: user ? user.email : '',
185 userIsActive: user ? user.isActive : false,
186 token: this.getApiToken(),
189 uuid: user ? user.uuid : '',
190 status: SessionStatus.VALIDATED,
191 apiRevision: cfg.apiRevision,
193 const localSessions = this.getSessions().map(s => ({
196 status: SessionStatus.INVALIDATED
199 const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
200 const remoteHost = cfg.remoteHosts[clusterId];
211 status: SessionStatus.INVALIDATED,
215 const sessions = [currentSession]
217 .concat(localSessions)
218 .filter((r: Session) => r.clusterId !== "*");
220 const uniqSessions = uniqBy(sessions, 'clusterId');