fix: Simplify admin guard to trust auth signal instead of localStorage

This commit is contained in:
Mahi
2026-02-09 15:32:15 -04:00
parent a4da9b5613
commit 4a5bf16827
2 changed files with 12 additions and 14 deletions

View File

@@ -118,22 +118,14 @@ export const adminGuard: CanActivateFn = (route, state) => {
return false;
}
// Double-check user type from stored user data
const storage = inject(StorageService);
const storedUser = storage.getUser<{ type?: string }>();
console.log('[ADMIN GUARD DEBUG] isAdmin():', authService.isAdmin(), 'storedUser?.type:', storedUser?.type, 'storedUser:', storedUser);
// Verify both signal and stored data agree on admin status
if (authService.isAdmin() && storedUser?.type === 'ADMIN') {
// Trust the auth service signal - it's set from the validated API response
// Note: localStorage checks removed due to race condition issues with storage events
if (authService.isAdmin()) {
console.log('[ADMIN GUARD] Access granted - user is admin');
return true;
}
// Log potential privilege escalation attempt
if (authService.isAdmin() !== (storedUser?.type === 'ADMIN')) {
console.warn('Admin guard: User type mismatch detected - isAdmin():', authService.isAdmin(), 'storedType:', storedUser?.type);
}
console.log('[ADMIN GUARD] Access denied - isAdmin():', authService.isAdmin());
notification.error('This page is only accessible to administrators.');
router.navigate(['/dashboard']);
return false;

View File

@@ -114,7 +114,9 @@ export class StorageService {
* Get user with sanitization
*/
getUser<T>(): T | null {
console.log('[STORAGE DEBUG] getUser called, key:', environment.userStorageKey);
const user = this.persistentStorage.getItem(environment.userStorageKey);
console.log('[STORAGE DEBUG] Raw user from storage:', user ? user.substring(0, 50) + '...' : 'NULL');
if (user) {
try {
const parsed = JSON.parse(user) as T;
@@ -137,16 +139,20 @@ export class StorageService {
* Set user with sanitization
*/
setUser<T>(user: T): void {
console.log('[STORAGE DEBUG] setUser called with:', user);
if (!user || typeof user !== 'object') {
console.warn('[STORAGE DEBUG] setUser - invalid user, skipping');
return;
}
try {
// Create a sanitized copy removing any potentially dangerous properties
const sanitized = this.sanitizeUserObject(user);
console.log('[STORAGE DEBUG] Storing user with key:', environment.userStorageKey, 'sanitized:', sanitized);
this.persistentStorage.setItem(environment.userStorageKey, JSON.stringify(sanitized));
console.log('[STORAGE DEBUG] User stored, localStorage contents:', Object.keys(localStorage));
} catch (error) {
console.error('Failed to store user:', error);
console.error('[STORAGE DEBUG] Failed to store user:', error);
}
}