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:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
import {HttpErrorResponse, HttpHandlerFn, HttpRequest, HttpResponse} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {Observable, Subject, firstValueFrom, of, throwError} from 'rxjs';
|
||||
import { HttpErrorResponse, HttpHandlerFn, HttpRequest, HttpResponse } from '@angular/common/http';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { Observable, Subject, firstValueFrom, of, throwError } from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {AuthInterceptorService} from './auth-interceptor.service';
|
||||
import { API_CONFIG } from '../config/api-config';
|
||||
import { AuthService } from '../../shared/service/auth.service';
|
||||
import { AuthInterceptorService } from './auth-interceptor.service';
|
||||
|
||||
describe('AuthInterceptorService', () => {
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
internalRefreshToken: vi.fn<() => Observable<{accessToken: string; refreshToken: string}>>(),
|
||||
internalRefreshToken: vi.fn<() => Observable<{ accessToken: string; refreshToken: string }>>(),
|
||||
saveInternalTokens: vi.fn<(accessToken: string, refreshToken: string) => void>(),
|
||||
logout: vi.fn<() => void>(),
|
||||
};
|
||||
@@ -28,7 +28,7 @@ describe('AuthInterceptorService', () => {
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: AuthService, useValue: authService},
|
||||
{ provide: AuthService, useValue: authService },
|
||||
]
|
||||
});
|
||||
|
||||
@@ -44,7 +44,7 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('adds the bearer token to API requests', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({status: 200, body: request.headers.get('Authorization')})));
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({ status: 200, body: request.headers.get('Authorization') })));
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
@@ -57,7 +57,7 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('does not add auth headers to non-api requests', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')})));
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({ status: 200, body: request.headers.has('Authorization') })));
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${API_CONFIG.BASE_URL}/assets/logo.svg`),
|
||||
@@ -69,7 +69,7 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('forwards api requests unchanged when no token is available', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')})));
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => of(new HttpResponse({ status: 200, body: request.headers.has('Authorization') })));
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
@@ -82,14 +82,14 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('retries a 401 request after a successful refresh', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(of({accessToken: 'fresh-token', refreshToken: 'refresh-token'}));
|
||||
authService.internalRefreshToken.mockReturnValue(of({ accessToken: 'fresh-token', refreshToken: 'refresh-token' }));
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (authHeader === 'Bearer fresh-token') {
|
||||
return of(new HttpResponse({status: 200, body: authHeader}));
|
||||
return of(new HttpResponse({ status: 200, body: authHeader }));
|
||||
}
|
||||
return throwError(() => new HttpErrorResponse({status: 401}));
|
||||
return throwError(() => new HttpErrorResponse({ status: 401 }));
|
||||
});
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
@@ -104,13 +104,13 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('retries a 401 request without persisting tokens when the refresh response is incomplete', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(of({accessToken: 'fresh-token', refreshToken: ''}));
|
||||
authService.internalRefreshToken.mockReturnValue(of({ accessToken: 'fresh-token', refreshToken: '' }));
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
if (request.headers.get('Authorization') === 'Bearer fresh-token') {
|
||||
return of(new HttpResponse({status: 200, body: request.headers.get('Authorization')}));
|
||||
return of(new HttpResponse({ status: 200, body: request.headers.get('Authorization') }));
|
||||
}
|
||||
return throwError(() => new HttpErrorResponse({status: 401}));
|
||||
return throwError(() => new HttpErrorResponse({ status: 401 }));
|
||||
});
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
@@ -125,10 +125,10 @@ describe('AuthInterceptorService', () => {
|
||||
it('logs out when the refresh request fails', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(
|
||||
throwError(() => new HttpErrorResponse({status: 500}))
|
||||
throwError(() => new HttpErrorResponse({ status: 500 }))
|
||||
);
|
||||
|
||||
const next = vi.fn(() => throwError(() => new HttpErrorResponse({status: 401})));
|
||||
const next = vi.fn(() => throwError(() => new HttpErrorResponse({ status: 401 })));
|
||||
|
||||
await expect(firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
@@ -140,7 +140,7 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('rethrows non-401 errors without logging out', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
const next = vi.fn(() => throwError(() => new HttpErrorResponse({status: 500})));
|
||||
const next = vi.fn(() => throwError(() => new HttpErrorResponse({ status: 500 })));
|
||||
|
||||
await expect(firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
@@ -153,21 +153,21 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('queues concurrent 401s behind a single refresh operation', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
const refreshSubject = new Subject<{accessToken: string; refreshToken: string}>();
|
||||
const refreshSubject = new Subject<{ accessToken: string; refreshToken: string }>();
|
||||
authService.internalRefreshToken.mockReturnValue(refreshSubject.asObservable());
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (authHeader === 'Bearer refreshed-token') {
|
||||
return of(new HttpResponse({status: 200, body: authHeader}));
|
||||
return of(new HttpResponse({ status: 200, body: authHeader }));
|
||||
}
|
||||
return throwError(() => new HttpErrorResponse({status: 401}));
|
||||
return throwError(() => new HttpErrorResponse({ status: 401 }));
|
||||
});
|
||||
|
||||
const firstRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/books`), next));
|
||||
const secondRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/libraries`), next));
|
||||
|
||||
refreshSubject.next({accessToken: 'refreshed-token', refreshToken: 'refresh-token'});
|
||||
refreshSubject.next({ accessToken: 'refreshed-token', refreshToken: 'refresh-token' });
|
||||
refreshSubject.complete();
|
||||
|
||||
const [firstResponse, secondResponse] = await Promise.all([firstRequest, secondRequest]);
|
||||
@@ -179,7 +179,7 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
describe('isExcludedAuthRequest', () => {
|
||||
const next = vi.fn((request: HttpRequest<unknown>) =>
|
||||
of(new HttpResponse({status: 200, body: request.headers.has('Authorization')}))
|
||||
of(new HttpResponse({ status: 200, body: request.headers.has('Authorization') }))
|
||||
);
|
||||
|
||||
it('excludes /api/v1/auth/login', async () => {
|
||||
@@ -212,6 +212,12 @@ describe('AuthInterceptorService', () => {
|
||||
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 () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('token-123');
|
||||
const response = await firstValueFrom(interceptor(new HttpRequest('GET', `${API_CONFIG.BASE_URL}/api/v1/auth/login-history`), next));
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http';
|
||||
import {inject} from '@angular/core';
|
||||
import {catchError, filter, switchMap, take} from 'rxjs/operators';
|
||||
import {BehaviorSubject, Observable, throwError, defer} from 'rxjs';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
import { HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { catchError, filter, switchMap, take } from 'rxjs/operators';
|
||||
import { BehaviorSubject, Observable, throwError, defer } from 'rxjs';
|
||||
import { AuthService } from '../../shared/service/auth.service';
|
||||
import { API_CONFIG } from '../config/api-config';
|
||||
|
||||
let isRefreshing = false;
|
||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||
@@ -22,6 +22,7 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
'/api/v1/auth/oidc/redirect',
|
||||
'/api/v1/auth/oidc/mobile/callback',
|
||||
'/api/v1/auth/oidc/backchannel-logout',
|
||||
'/api/v1/public-settings',
|
||||
];
|
||||
const urlPath = req.url.split('?')[0];
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user