NLP-IBM-Debater / src /app /utils /user.utils.ts
Yassine Mhirsi
fixed typescript adn added logout
2251e03
raw
history blame
1.7 kB
/**
* User-related utility functions
*/
const UNIQUE_ID_KEY = 'user_unique_id';
const USER_ID_KEY = 'user_id';
/**
* Get or create a unique browser identifier
*/
export function getOrCreateUniqueId(): string {
let uniqueId = localStorage.getItem(UNIQUE_ID_KEY);
if (!uniqueId) {
// Generate a UUID v4
uniqueId = crypto.randomUUID();
localStorage.setItem(UNIQUE_ID_KEY, uniqueId);
}
return uniqueId;
}
/**
* Get user ID from localStorage
*/
export function getUserId(): string | null {
return localStorage.getItem(USER_ID_KEY);
}
/**
* Set user ID in localStorage
*/
export function setUserId(userId: string): void {
localStorage.setItem(USER_ID_KEY, userId);
}
/**
* Set user ID and notify components of authentication change
* Use this when logging in or registering to ensure immediate UI updates
*/
export function setUserIdAndNotify(userId: string): void {
setUserId(userId);
// Dispatch custom event to immediately update all components using useAuth hook
window.dispatchEvent(new CustomEvent('authChange'));
}
/**
* Logout user by clearing data and notifying components
* Use this when logging out to ensure immediate UI updates
*/
export function logoutAndNotify(): void {
clearUserData();
// Dispatch custom event to immediately update all components using useAuth hook
window.dispatchEvent(new CustomEvent('authChange'));
}
/**
* Clear user data from localStorage
*/
export function clearUserData(): void {
localStorage.removeItem(USER_ID_KEY);
localStorage.removeItem(UNIQUE_ID_KEY);
}
/**
* Check if user is registered (has user_id)
*/
export function isUserRegistered(): boolean {
return getUserId() !== null;
}