1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { API_HOST, serverApi } from "../../common/api/server-api";
6 import { User } from "../../models/user";
7 import { Dispatch } from "redux";
8 import actions from "../../store/auth/auth-action";
10 export const API_TOKEN_KEY = 'apiToken';
11 export const USER_EMAIL_KEY = 'userEmail';
12 export const USER_FIRST_NAME_KEY = 'userFirstName';
13 export const USER_LAST_NAME_KEY = 'userLastName';
14 export const USER_UUID_KEY = 'userUuid';
15 export const USER_OWNER_UUID_KEY = 'userOwnerUuid';
17 export interface UserDetailsResponse {
26 export default class AuthService {
28 public saveApiToken(token: string) {
29 localStorage.setItem(API_TOKEN_KEY, token);
32 public removeApiToken() {
33 localStorage.removeItem(API_TOKEN_KEY);
36 public getApiToken() {
37 return localStorage.getItem(API_TOKEN_KEY) || undefined;
40 public getOwnerUuid() {
41 return localStorage.getItem(USER_OWNER_UUID_KEY) || undefined;
44 public getUser(): User | undefined {
45 const email = localStorage.getItem(USER_EMAIL_KEY);
46 const firstName = localStorage.getItem(USER_FIRST_NAME_KEY);
47 const lastName = localStorage.getItem(USER_LAST_NAME_KEY);
48 const uuid = localStorage.getItem(USER_UUID_KEY);
49 const ownerUuid = localStorage.getItem(USER_OWNER_UUID_KEY);
51 return email && firstName && lastName && uuid && ownerUuid
52 ? { email, firstName, lastName, uuid, ownerUuid }
56 public saveUser(user: User) {
57 localStorage.setItem(USER_EMAIL_KEY, user.email);
58 localStorage.setItem(USER_FIRST_NAME_KEY, user.firstName);
59 localStorage.setItem(USER_LAST_NAME_KEY, user.lastName);
60 localStorage.setItem(USER_UUID_KEY, user.uuid);
61 localStorage.setItem(USER_OWNER_UUID_KEY, user.ownerUuid);
65 localStorage.removeItem(USER_EMAIL_KEY);
66 localStorage.removeItem(USER_FIRST_NAME_KEY);
67 localStorage.removeItem(USER_LAST_NAME_KEY);
68 localStorage.removeItem(USER_UUID_KEY);
69 localStorage.removeItem(USER_OWNER_UUID_KEY);
73 const currentUrl = `${window.location.protocol}//${window.location.host}/token`;
74 window.location.assign(`${API_HOST}/login?return_to=${currentUrl}`);
78 const currentUrl = `${window.location.protocol}//${window.location.host}`;
79 window.location.assign(`${API_HOST}/logout?return_to=${currentUrl}`);
82 public getUserDetails = () => (dispatch: Dispatch): Promise<void> => {
83 dispatch(actions.USER_DETAILS_REQUEST());
85 .get<UserDetailsResponse>('/users/current')
87 dispatch(actions.USER_DETAILS_SUCCESS(resp.data));
91 public getRootUuid() {
92 const uuid = this.getOwnerUuid();
93 const uuidParts = uuid ? uuid.split('-') : [];
94 return uuidParts.length > 1 ? `${uuidParts[0]}-${uuidParts[1]}` : undefined;