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) {
124 const currentUrl = `${window.location.protocol}//${window.location.host}`;
125 window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${currentUrl}`);
128 public getUserDetails = (showErrors?: boolean): Promise<User> => {
129 const reqId = uuid();
130 this.actions.progressFn(reqId, true);
131 return this.apiClient
132 .get<UserDetailsResponse>('/users/current')
134 this.actions.progressFn(reqId, false);
135 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
137 email: resp.data.email,
138 firstName: resp.data.first_name,
139 lastName: resp.data.last_name,
140 uuid: resp.data.uuid,
141 ownerUuid: resp.data.owner_uuid,
142 isAdmin: resp.data.is_admin,
143 isActive: resp.data.is_active,
144 username: resp.data.username,
149 this.actions.progressFn(reqId, false);
150 this.actions.errorFn(reqId, e, showErrors);
155 public getSessions(): Session[] {
157 const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
164 public saveSessions(sessions: Session[]) {
165 this.removeSessions();
166 this.getStorage().setItem("sessions", JSON.stringify(sessions));
169 public removeSessions() {
170 localStorage.removeItem("sessions");
171 sessionStorage.removeItem("sessions");
174 public buildSessions(cfg: Config, user?: User) {
175 const currentSession = {
176 clusterId: cfg.uuidPrefix,
177 remoteHost: cfg.rootUrl,
178 baseUrl: cfg.baseUrl,
179 name: user ? getUserDisplayName(user) : '',
180 email: user ? user.email : '',
181 userIsActive: user ? user.isActive : false,
182 token: this.getApiToken(),
185 uuid: user ? user.uuid : '',
186 status: SessionStatus.VALIDATED,
187 apiRevision: cfg.apiRevision,
189 const localSessions = this.getSessions().map(s => ({
192 status: SessionStatus.INVALIDATED
195 const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
196 const remoteHost = cfg.remoteHosts[clusterId];
207 status: SessionStatus.INVALIDATED,
211 const sessions = [currentSession]
213 .concat(localSessions)
214 .filter((r: Session) => r.clusterId !== "*");
216 const uniqSessions = uniqBy(sessions, 'clusterId');