File size: 1,695 Bytes
b6bed80 2251e03 b6bed80 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
/**
* 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;
}
|