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 * as 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';
26 export interface UserDetailsResponse {
38 export class AuthService {
41 protected apiClient: AxiosInstance,
42 protected baseUrl: string,
43 protected actions: ApiActions,
44 protected useSessionStorage: boolean = false) { }
46 private getStorage() {
47 if (this.useSessionStorage) {
48 return sessionStorage;
53 public saveApiToken(token: string) {
54 this.removeApiToken();
55 this.getStorage().setItem(API_TOKEN_KEY, token);
56 const sp = token.split('/');
57 if (sp.length === 3) {
58 this.getStorage().setItem(HOME_CLUSTER, sp[1].substr(0, 5));
62 public removeTargetURL() {
63 localStorage.removeItem(TARGET_URL);
64 sessionStorage.removeItem(TARGET_URL);
67 public getTargetURL() {
68 return this.getStorage().getItem(TARGET_URL);
71 public removeApiToken() {
72 localStorage.removeItem(API_TOKEN_KEY);
73 sessionStorage.removeItem(API_TOKEN_KEY);
76 public getApiToken() {
77 return this.getStorage().getItem(API_TOKEN_KEY) || undefined;
80 public getHomeCluster() {
81 return this.getStorage().getItem(HOME_CLUSTER) || undefined;
84 public getApiClient() {
85 return this.apiClient;
89 [localStorage, sessionStorage].forEach((storage) => {
90 storage.removeItem(USER_EMAIL_KEY);
91 storage.removeItem(USER_FIRST_NAME_KEY);
92 storage.removeItem(USER_LAST_NAME_KEY);
93 storage.removeItem(USER_UUID_KEY);
94 storage.removeItem(USER_OWNER_UUID_KEY);
95 storage.removeItem(USER_IS_ADMIN);
96 storage.removeItem(USER_IS_ACTIVE);
97 storage.removeItem(USER_USERNAME);
98 storage.removeItem(USER_PREFS);
99 storage.removeItem(TARGET_URL);
103 public login(uuidPrefix: string, homeCluster: string, loginCluster: string, remoteHosts: { [key: string]: string }) {
104 const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
105 const homeClusterHost = remoteHosts[homeCluster];
106 const rd = new URL(window.location.href);
107 this.getStorage().setItem(TARGET_URL, rd.pathname + rd.search);
108 window.location.assign(`https://${homeClusterHost}/login?${(uuidPrefix !== homeCluster && homeCluster !== loginCluster) ? "remote=" + uuidPrefix + "&" : ""}return_to=${currentUrl}`);
111 public logout(expireToken: string) {
112 const currentUrl = `${window.location.protocol}//${window.location.host}`;
113 window.location.assign(`${this.baseUrl || ""}/logout?api_token=${expireToken}&return_to=${currentUrl}`);
116 public getUserDetails = (showErrors?: boolean): Promise<User> => {
117 const reqId = uuid();
118 this.actions.progressFn(reqId, true);
119 return this.apiClient
120 .get<UserDetailsResponse>('/users/current')
122 this.actions.progressFn(reqId, false);
123 const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {} };
125 email: resp.data.email,
126 firstName: resp.data.first_name,
127 lastName: resp.data.last_name,
128 uuid: resp.data.uuid,
129 ownerUuid: resp.data.owner_uuid,
130 isAdmin: resp.data.is_admin,
131 isActive: resp.data.is_active,
132 username: resp.data.username,
137 this.actions.progressFn(reqId, false);
138 this.actions.errorFn(reqId, e, showErrors);
143 public getSessions(): Session[] {
145 const sessions = JSON.parse(this.getStorage().getItem("sessions") || '');
152 public saveSessions(sessions: Session[]) {
153 this.removeSessions();
154 this.getStorage().setItem("sessions", JSON.stringify(sessions));
157 public removeSessions() {
158 localStorage.removeItem("sessions");
159 sessionStorage.removeItem("sessions");
162 public buildSessions(cfg: Config, user?: User) {
163 const currentSession = {
164 clusterId: cfg.uuidPrefix,
165 remoteHost: cfg.rootUrl,
166 baseUrl: cfg.baseUrl,
167 name: user ? getUserDisplayName(user) : '',
168 email: user ? user.email : '',
169 userIsActive: user ? user.isActive : false,
170 token: this.getApiToken(),
173 uuid: user ? user.uuid : '',
174 status: SessionStatus.VALIDATED,
175 apiRevision: cfg.apiRevision,
177 const localSessions = this.getSessions().map(s => ({
180 status: SessionStatus.INVALIDATED
183 const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => {
184 const remoteHost = cfg.remoteHosts[clusterId];
195 status: SessionStatus.INVALIDATED,
199 const sessions = [currentSession]
201 .concat(localSessions)
202 .filter((r: Session) => r.clusterId !== "*");
204 const uniqSessions = uniqBy(sessions, 'clusterId');