1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { User } from "../../models/user";
6 import { AxiosInstance } from "../../../node_modules/axios";
8 export const API_TOKEN_KEY = 'apiToken';
9 export const USER_EMAIL_KEY = 'userEmail';
10 export const USER_FIRST_NAME_KEY = 'userFirstName';
11 export const USER_LAST_NAME_KEY = 'userLastName';
12 export const USER_UUID_KEY = 'userUuid';
13 export const USER_OWNER_UUID_KEY = 'userOwnerUuid';
15 export interface UserDetailsResponse {
24 export class AuthService {
27 protected apiClient: AxiosInstance,
28 protected baseUrl: string) { }
30 public saveApiToken(token: string) {
31 localStorage.setItem(API_TOKEN_KEY, token);
34 public removeApiToken() {
35 localStorage.removeItem(API_TOKEN_KEY);
38 public getApiToken() {
39 return localStorage.getItem(API_TOKEN_KEY) || undefined;
43 return localStorage.getItem(USER_UUID_KEY) || undefined;
46 public getOwnerUuid() {
47 return localStorage.getItem(USER_OWNER_UUID_KEY) || undefined;
50 public getUser(): User | undefined {
51 const email = localStorage.getItem(USER_EMAIL_KEY);
52 const firstName = localStorage.getItem(USER_FIRST_NAME_KEY);
53 const lastName = localStorage.getItem(USER_LAST_NAME_KEY);
54 const uuid = localStorage.getItem(USER_UUID_KEY);
55 const ownerUuid = localStorage.getItem(USER_OWNER_UUID_KEY);
57 return email && firstName && lastName && uuid && ownerUuid
58 ? { email, firstName, lastName, uuid, ownerUuid }
62 public saveUser(user: User) {
63 localStorage.setItem(USER_EMAIL_KEY, user.email);
64 localStorage.setItem(USER_FIRST_NAME_KEY, user.firstName);
65 localStorage.setItem(USER_LAST_NAME_KEY, user.lastName);
66 localStorage.setItem(USER_UUID_KEY, user.uuid);
67 localStorage.setItem(USER_OWNER_UUID_KEY, user.ownerUuid);
71 localStorage.removeItem(USER_EMAIL_KEY);
72 localStorage.removeItem(USER_FIRST_NAME_KEY);
73 localStorage.removeItem(USER_LAST_NAME_KEY);
74 localStorage.removeItem(USER_UUID_KEY);
75 localStorage.removeItem(USER_OWNER_UUID_KEY);
79 const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
80 window.location.assign(`${this.baseUrl || ""}/login?return_to=${currentUrl}`);
84 const currentUrl = `${window.location.protocol}//${window.location.host}`;
85 window.location.assign(`${this.baseUrl || ""}/logout?return_to=${currentUrl}`);
88 public getUserDetails = (): Promise<User> => {
90 .get<UserDetailsResponse>('/users/current')
92 email: resp.data.email,
93 firstName: resp.data.first_name,
94 lastName: resp.data.last_name,
96 ownerUuid: resp.data.owner_uuid
100 public getRootUuid() {
101 const uuid = this.getOwnerUuid();
102 const uuidParts = uuid ? uuid.split('-') : [];
103 return uuidParts.length > 1 ? `${uuidParts[0]}-${uuidParts[1]}` : undefined;