fix(auth): add global error handler and PWA update service, and update auth logout to force full page reload (prevent reload-hell) (#741)

This commit is contained in:
brios
2026-04-22 17:27:47 -04:00
committed by Zach Yale
parent 10afe3c826
commit 62434c590d
8 changed files with 243 additions and 111 deletions
@@ -0,0 +1,47 @@
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
const err = error instanceof Error ? error : undefined;
const message = typeof error === 'string' ? error : err?.message ?? '';
const name = err?.name ?? '';
const chunkFailedMessage = /Loading chunk [\d]+ failed/i;
const moduleFailedMessage = /Loading failed for the module/i;
const dynamicImportFailedMessage = /Failed to fetch dynamically imported module|Importing a module script failed/i;
if (
chunkFailedMessage.test(message) ||
moduleFailedMessage.test(message) ||
dynamicImportFailedMessage.test(message) ||
name === 'ChunkLoadError'
) {
console.error('Chunk/Module load failed. Forcing reload to fetch latest version...', error);
// Prevent infinite reload loop if the reload itself fails
const now = Date.now();
let shouldReload = true;
try {
const lastReloadValue = localStorage.getItem('last_chunk_error_reload');
const lastReload = Number(lastReloadValue);
shouldReload = !Number.isFinite(lastReload) || now - lastReload > 10000;
if (shouldReload) {
localStorage.setItem('last_chunk_error_reload', now.toString());
}
} catch (storageError) {
console.warn('Could not access reload guard storage; reloading anyway.', storageError);
}
if (shouldReload) {
window.location.reload();
} else {
console.error('Chunk load failed multiple times in a short period. Stopped reloading to avoid loop.');
}
} else {
console.error('An unexpected error occurred:', error);
}
}
}
@@ -212,6 +212,12 @@ describe('AuthInterceptorService', () => {
expect((response as HttpResponse<boolean>).body).toBe(false); expect((response as HttpResponse<boolean>).body).toBe(false);
}); });
it('excludes /api/v1/public-settings', async () => {
authService.getInternalAccessToken.mockReturnValue('token-123');
const response = await firstValueFrom(interceptor(new HttpRequest('GET', `${API_CONFIG.BASE_URL}/api/v1/public-settings`), next));
expect((response as HttpResponse<boolean>).body).toBe(false);
});
it('does NOT exclude /api/v1/auth/login-history (exact match test)', async () => { it('does NOT exclude /api/v1/auth/login-history (exact match test)', async () => {
authService.getInternalAccessToken.mockReturnValue('token-123'); authService.getInternalAccessToken.mockReturnValue('token-123');
const response = await firstValueFrom(interceptor(new HttpRequest('GET', `${API_CONFIG.BASE_URL}/api/v1/auth/login-history`), next)); const response = await firstValueFrom(interceptor(new HttpRequest('GET', `${API_CONFIG.BASE_URL}/api/v1/auth/login-history`), next));
@@ -22,6 +22,7 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
'/api/v1/auth/oidc/redirect', '/api/v1/auth/oidc/redirect',
'/api/v1/auth/oidc/mobile/callback', '/api/v1/auth/oidc/mobile/callback',
'/api/v1/auth/oidc/backchannel-logout', '/api/v1/auth/oidc/backchannel-logout',
'/api/v1/public-settings',
]; ];
const urlPath = req.url.split('?')[0]; const urlPath = req.url.split('?')[0];
const isAuthRequest = authExcludePaths.some(path => urlPath === `${API_CONFIG.BASE_URL}${path}`); const isAuthRequest = authExcludePaths.some(path => urlPath === `${API_CONFIG.BASE_URL}${path}`);
@@ -0,0 +1,51 @@
import { inject, Injectable } from '@angular/core';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PwaUpdateService {
private swUpdate = inject(SwUpdate);
constructor() {
if (this.swUpdate.isEnabled) {
this.swUpdate.versionUpdates
.pipe(filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'))
.subscribe((evt) => {
console.info('New version available. Refreshing...');
const hash = evt.latestVersion.hash;
if (this.shouldReload(`version_${hash}`)) {
window.location.reload();
}
});
this.swUpdate.unrecoverable.subscribe(event => {
console.error('Service Worker entered unrecoverable state:', event.reason);
if (this.shouldReload(`unrecoverable_${event.reason}`)) {
window.location.reload();
}
});
}
}
private shouldReload(reason: string): boolean {
const key = 'pwa_reload_guard';
const now = Date.now();
try {
const guardStr = sessionStorage.getItem(key);
const guard = guardStr ? JSON.parse(guardStr) : null;
if (guard && guard.reason === reason && now - guard.timestamp < 10000) {
console.error(`PWA reload guard triggered for reason: ${reason}. Stopped reloading to avoid loop.`);
return false;
}
sessionStorage.setItem(key, JSON.stringify({ reason, timestamp: now }));
return true;
} catch (e) {
console.warn('PWA reload guard could not access sessionStorage', e);
return true;
}
}
}
@@ -49,6 +49,10 @@ describe('AuthService', () => {
service = TestBed.inject(AuthService); service = TestBed.inject(AuthService);
httpTestingController = TestBed.inject(HttpTestingController); httpTestingController = TestBed.inject(HttpTestingController);
// Mock redirectTo for all tests using a narrow test-only type to access protected method
vi.spyOn(service as unknown as { redirectTo: AuthService['redirectTo'] }, 'redirectTo')
.mockImplementation(() => undefined);
}); });
afterEach(() => { afterEach(() => {
@@ -111,7 +115,7 @@ describe('AuthService', () => {
expect(service.token()).toBeNull(); expect(service.token()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce(); expect(rxStompService.deactivate).toHaveBeenCalledOnce();
expect(router.navigate).toHaveBeenCalledWith(['/login']); expect((service as unknown as { redirectTo: AuthService['redirectTo'] }).redirectTo).toHaveBeenCalledWith('/login', true);
}); });
it('logs out locally when the backend logout request fails', async () => { it('logs out locally when the backend logout request fails', async () => {
@@ -127,7 +131,7 @@ describe('AuthService', () => {
expect(service.token()).toBeNull(); expect(service.token()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce(); expect(rxStompService.deactivate).toHaveBeenCalledOnce();
expect(router.navigate).toHaveBeenCalledWith(['/login']); expect((service as unknown as { redirectTo: AuthService['redirectTo'] }).redirectTo).toHaveBeenCalledWith('/login', true);
}); });
it('clears the session and navigates with a reason during force logout', () => { it('clears the session and navigates with a reason during force logout', () => {
@@ -138,9 +142,7 @@ describe('AuthService', () => {
expect(service.token()).toBeNull(); expect(service.token()).toBeNull();
expect(rxStompService.deactivate).toHaveBeenCalledOnce(); expect(rxStompService.deactivate).toHaveBeenCalledOnce();
expect(router.navigate).toHaveBeenCalledWith(['/login'], { expect((service as unknown as { redirectTo: AuthService['redirectTo'] }).redirectTo).toHaveBeenCalledWith('/login?reason=session_revoked', true);
queryParams: {reason: 'session_revoked'},
});
}); });
it('clears the session when the login page is opened', () => { it('clears the session when the login page is opened', () => {
+32 -13
View File
@@ -1,6 +1,6 @@
import { computed, inject, Injectable, Injector, signal } from '@angular/core'; import { computed, inject, Injectable, Injector, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import {Observable, tap} from 'rxjs'; import { Observable, tap, finalize } from 'rxjs';
import { RxStompService } from '../websocket/rx-stomp.service'; import { RxStompService } from '../websocket/rx-stomp.service';
import { API_CONFIG } from '../../core/config/api-config'; import { API_CONFIG } from '../../core/config/api-config';
import { createRxStompConfig } from '../websocket/rx-stomp.config'; import { createRxStompConfig } from '../websocket/rx-stomp.config';
@@ -14,7 +14,10 @@ export class AuthService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`; private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`;
private rxStompService?: RxStompService; private rxStompService?: RxStompService;
private postLoginInitialized = false; private readonly _postLoginInitialized = signal(false);
readonly postLoginInitialized = this._postLoginInitialized.asReadonly();
private readonly _logoutInProgress = signal(false);
readonly logoutInProgress = this._logoutInProgress.asReadonly();
private http = inject(HttpClient); private http = inject(HttpClient);
private injector = inject(Injector); private injector = inject(Injector);
@@ -74,26 +77,42 @@ export class AuthService {
} }
logout(): void { logout(): void {
if (this._logoutInProgress()) return;
this._logoutInProgress.set(true);
const refreshToken = this.getInternalRefreshToken(); const refreshToken = this.getInternalRefreshToken();
this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, {refreshToken}).subscribe({ this.clearSession();
this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, { refreshToken })
.pipe(finalize(() => {
this._logoutInProgress.set(false);
}))
.subscribe({
next: (response) => { next: (response) => {
if (response.logoutUrl) { if (response.logoutUrl) {
window.location.href = response.logoutUrl; this.redirectTo(response.logoutUrl, true);
} else { } else {
this.clearSession(); this.redirectTo('/login', true);
this.router.navigate(['/login']).then(() => window.location.reload());
} }
}, },
error: () => { error: () => {
this.clearSession(); this.redirectTo('/login', true);
this.router.navigate(['/login']).then(() => window.location.reload());
} }
}); });
} }
forceLogout(reason: string): void { forceLogout(reason: string): void {
this._logoutInProgress.set(true);
this.clearSession(); this.clearSession();
this.router.navigate(['/login'], {queryParams: {reason}}); this.redirectTo(`/login?reason=${encodeURIComponent(reason)}`, true);
}
protected redirectTo(url: string, replace = false): void {
if (replace) {
window.location.replace(url);
} else {
window.location.href = url;
}
} }
clearSessionOnLoginPage(): void { clearSessionOnLoginPage(): void {
@@ -104,7 +123,7 @@ export class AuthService {
localStorage.removeItem('accessToken_Internal'); localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('refreshToken_Internal'); localStorage.removeItem('refreshToken_Internal');
this.token.set(null); this.token.set(null);
this.postLoginInitialized = false; this._postLoginInitialized.set(false);
this.getRxStompService().deactivate(); this.getRxStompService().deactivate();
} }
@@ -124,14 +143,14 @@ export class AuthService {
stompService.updateConfig(config); stompService.updateConfig(config);
stompService.activate(); stompService.activate();
if (!this.postLoginInitialized) { if (!this._postLoginInitialized()) {
this.handleSuccessfulAuth(); this.handleSuccessfulAuth();
} }
} }
private handleSuccessfulAuth() { private handleSuccessfulAuth() {
if (this.postLoginInitialized) return; if (this._postLoginInitialized()) return;
this.postLoginInitialized = true; this._postLoginInitialized.set(true);
this.postLoginInitializer.initialize().subscribe({ this.postLoginInitializer.initialize().subscribe({
next: () => console.log('AuthService: Post-login initialization completed'), next: () => console.log('AuthService: Post-login initialization completed'),
error: (err) => console.error('AuthService: Post-login initialization failed:', err) error: (err) => console.error('AuthService: Post-login initialization failed:', err)
+7 -1
View File
@@ -1,4 +1,5 @@
import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { ErrorHandler, inject, isDevMode, provideAppInitializer, provideZonelessChangeDetection } from '@angular/core';
import { DialogService } from 'primeng/dynamicdialog'; import { DialogService } from 'primeng/dynamicdialog';
import { ConfirmationService, MessageService } from 'primeng/api'; import { ConfirmationService, MessageService } from 'primeng/api';
import { RxStompService } from './app/shared/websocket/rx-stomp.service'; import { RxStompService } from './app/shared/websocket/rx-stomp.service';
@@ -12,7 +13,8 @@ import Aura from './app/shared/layout/theme-palette-extend';
import { routes } from './app/app.routes'; import { routes } from './app/app.routes';
import { AuthInterceptorService } from './app/core/security/auth-interceptor.service'; import { AuthInterceptorService } from './app/core/security/auth-interceptor.service';
import { AuthService, websocketInitializer } from './app/shared/service/auth.service'; import { AuthService, websocketInitializer } from './app/shared/service/auth.service';
import { inject, isDevMode, provideAppInitializer, provideZonelessChangeDetection } from '@angular/core'; import { GlobalErrorHandler } from './app/core/errors/global-error-handler';
import { PwaUpdateService } from './app/core/services/pwa-update.service';
import { initializeAuthFactory } from './app/core/security/auth-initializer'; import { initializeAuthFactory } from './app/core/security/auth-initializer';
import { StartupService } from './app/shared/service/startup.service'; import { StartupService } from './app/shared/service/startup.service';
import { provideCharts, withDefaultRegisterables } from 'ng2-charts'; import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
@@ -80,6 +82,10 @@ bootstrapApplication(AppComponent, {
}), provideServiceWorker('ngsw-worker.js', { }), provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(), enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:30000' registrationStrategy: 'registerWhenStable:30000'
}),
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
provideAppInitializer(() => {
inject(PwaUpdateService);
}) })
] ]
}).catch(err => console.error(err)); }).catch(err => console.error(err));