fix: Prevent storage listener from clearing auth during login

The storage event was firing when user was saved to localStorage,
causing loadStoredUser() to run and clear the auth state.

Added isLoginInProgress guard to skip storage events during login.
This commit is contained in:
Mahi
2026-02-09 15:04:28 -04:00
parent df5210a3c8
commit 5b6f452b09

View File

@@ -68,6 +68,9 @@ export class AuthService implements OnDestroy {
// Track storage listener for cleanup // Track storage listener for cleanup
private storageListener: ((event: StorageEvent) => void) | null = null; private storageListener: ((event: StorageEvent) => void) | null = null;
// Guard to prevent storage listener from interfering during login
private isLoginInProgress = false;
constructor() { constructor() {
this.loadStoredUser(); this.loadStoredUser();
this.setupStorageListener(); this.setupStorageListener();
@@ -122,6 +125,12 @@ export class AuthService implements OnDestroy {
private setupStorageListener(): void { private setupStorageListener(): void {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
this.storageListener = (event: StorageEvent) => { this.storageListener = (event: StorageEvent) => {
// Skip if login is in progress to avoid race conditions
if (this.isLoginInProgress) {
console.log('[AUTH DEBUG] Skipping storage event during login');
return;
}
this.ngZone.run(() => { this.ngZone.run(() => {
if (event.key === null || event.key?.includes('token') || event.key?.includes('user')) { if (event.key === null || event.key?.includes('token') || event.key?.includes('user')) {
// Storage was cleared or auth-related key changed // Storage was cleared or auth-related key changed
@@ -210,6 +219,7 @@ export class AuthService implements OnDestroy {
} }
this._isLoading.set(true); this._isLoading.set(true);
this.isLoginInProgress = true;
try { try {
const response = await firstValueFrom( const response = await firstValueFrom(
@@ -266,6 +276,7 @@ export class AuthService implements OnDestroy {
this.storage.setUser(user); this.storage.setUser(user);
this.updateAuthState(user, true); this.updateAuthState(user, true);
} finally { } finally {
this.isLoginInProgress = false;
this._isLoading.set(false); this._isLoading.set(false);
} }
} }