ui-nyla/src/utils/userCache.ts

75 lines
2.5 KiB
TypeScript

/**
* User Data Cache Management
*
* Centralized user data storage using sessionStorage for security.
* sessionStorage is cleared when the browser tab/window closes, making it more secure than localStorage.
*
* Flow:
* 1. Login → Authentication hooks (useAuthentication.ts, useUsers.ts) set user data
* 2. Components/Checkers → Read user data from cache
* 3. Logout → Clear user data cache
*/
const USER_CACHE_KEY = '__user_cache__';
export interface CachedUserData {
id: string;
username: string;
email: string;
fullName: string;
privilege?: string; // Deprecated - use roleLabels instead
roleLabels?: string[]; // Array of role labels from backend (e.g., ["user"])
// mandateId entfernt - User gehört keinem Mandanten direkt an
// Stattdessen hat er Zugriff auf Feature-Instanzen (siehe featureStore)
isSysAdmin?: boolean; // Infrastructure/System Operator (RBAC bypass)
isPlatformAdmin?: boolean; // Cross-Mandate Governance (no RBAC bypass)
language: string;
enabled: boolean;
authenticationAuthority: string;
}
/**
* Set user data in sessionStorage cache
* Called by authentication hooks after successful login
*/
export const setUserDataCache = (userData: CachedUserData): void => {
if (userData) {
// Always cache user data - permissions are checked via RBAC API, not client-side
// roleLabels/privilege are optional metadata, not required for app functionality
try {
sessionStorage.setItem(USER_CACHE_KEY, JSON.stringify(userData));
// Notify listeners (e.g. LanguageProvider) that user data has changed.
// This ensures the UI language syncs after login/refresh/profile update.
window.dispatchEvent(new CustomEvent('userInfoUpdated'));
} catch (error) {
console.error('Failed to cache user data:', error);
}
}
};
/**
* Get user data from sessionStorage cache
* Called by components and privilege checkers
*/
export const getUserDataCache = (): CachedUserData | null => {
try {
const cached = sessionStorage.getItem(USER_CACHE_KEY);
if (cached) {
return JSON.parse(cached);
}
} catch (error) {
console.error('Failed to parse user data from cache:', error);
// Clear corrupted data
sessionStorage.removeItem(USER_CACHE_KEY);
}
return null;
};
/**
* Clear user data cache
* Called on logout
*/
export const clearUserDataCache = (): void => {
sessionStorage.removeItem(USER_CACHE_KEY);
};