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);
}
}
}
@@ -1,16 +1,16 @@
import {HttpErrorResponse, HttpHandlerFn, HttpRequest, HttpResponse} from '@angular/common/http'; import { HttpErrorResponse, HttpHandlerFn, HttpRequest, HttpResponse } from '@angular/common/http';
import {TestBed} from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {Observable, Subject, firstValueFrom, of, throwError} from 'rxjs'; import { Observable, Subject, firstValueFrom, of, throwError } from 'rxjs';
import {API_CONFIG} from '../config/api-config'; import { API_CONFIG } from '../config/api-config';
import {AuthService} from '../../shared/service/auth.service'; import { AuthService } from '../../shared/service/auth.service';
import {AuthInterceptorService} from './auth-interceptor.service'; import { AuthInterceptorService } from './auth-interceptor.service';
describe('AuthInterceptorService', () => { describe('AuthInterceptorService', () => {
const authService = { const authService = {
getInternalAccessToken: vi.fn<() => string | null>(), 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>(), saveInternalTokens: vi.fn<(accessToken: string, refreshToken: string) => void>(),
logout: vi.fn<() => void>(), logout: vi.fn<() => void>(),
}; };
@@ -28,7 +28,7 @@ describe('AuthInterceptorService', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ providers: [
{provide: AuthService, useValue: authService}, { provide: AuthService, useValue: authService },
] ]
}); });
@@ -44,7 +44,7 @@ describe('AuthInterceptorService', () => {
it('adds the bearer token to API requests', async () => { it('adds the bearer token to API requests', async () => {
authService.getInternalAccessToken.mockReturnValue('token-123'); 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( const response = await firstValueFrom(interceptor(
new HttpRequest('GET', `${apiUrl}/books`), new HttpRequest('GET', `${apiUrl}/books`),
@@ -57,7 +57,7 @@ describe('AuthInterceptorService', () => {
it('does not add auth headers to non-api requests', async () => { it('does not add auth headers to non-api requests', async () => {
authService.getInternalAccessToken.mockReturnValue('token-123'); 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( const response = await firstValueFrom(interceptor(
new HttpRequest('GET', `${API_CONFIG.BASE_URL}/assets/logo.svg`), 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 () => { it('forwards api requests unchanged when no token is available', async () => {
authService.getInternalAccessToken.mockReturnValue(null); 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( const response = await firstValueFrom(interceptor(
new HttpRequest('GET', `${apiUrl}/books`), new HttpRequest('GET', `${apiUrl}/books`),
@@ -82,14 +82,14 @@ describe('AuthInterceptorService', () => {
it('retries a 401 request after a successful refresh', async () => { it('retries a 401 request after a successful refresh', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token'); 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 next = vi.fn((request: HttpRequest<unknown>) => {
const authHeader = request.headers.get('Authorization'); const authHeader = request.headers.get('Authorization');
if (authHeader === 'Bearer fresh-token') { 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( 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 () => { it('retries a 401 request without persisting tokens when the refresh response is incomplete', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token'); 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>) => { const next = vi.fn((request: HttpRequest<unknown>) => {
if (request.headers.get('Authorization') === 'Bearer fresh-token') { 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( const response = await firstValueFrom(interceptor(
@@ -125,10 +125,10 @@ describe('AuthInterceptorService', () => {
it('logs out when the refresh request fails', async () => { it('logs out when the refresh request fails', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token'); authService.getInternalAccessToken.mockReturnValue('expired-token');
authService.internalRefreshToken.mockReturnValue( 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( await expect(firstValueFrom(interceptor(
new HttpRequest('GET', `${apiUrl}/books`), new HttpRequest('GET', `${apiUrl}/books`),
@@ -140,7 +140,7 @@ describe('AuthInterceptorService', () => {
it('rethrows non-401 errors without logging out', async () => { it('rethrows non-401 errors without logging out', async () => {
authService.getInternalAccessToken.mockReturnValue('token-123'); 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( await expect(firstValueFrom(interceptor(
new HttpRequest('GET', `${apiUrl}/books`), new HttpRequest('GET', `${apiUrl}/books`),
@@ -153,21 +153,21 @@ describe('AuthInterceptorService', () => {
it('queues concurrent 401s behind a single refresh operation', async () => { it('queues concurrent 401s behind a single refresh operation', async () => {
authService.getInternalAccessToken.mockReturnValue('expired-token'); 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()); authService.internalRefreshToken.mockReturnValue(refreshSubject.asObservable());
const next = vi.fn((request: HttpRequest<unknown>) => { const next = vi.fn((request: HttpRequest<unknown>) => {
const authHeader = request.headers.get('Authorization'); const authHeader = request.headers.get('Authorization');
if (authHeader === 'Bearer refreshed-token') { 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 firstRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/books`), next));
const secondRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/libraries`), 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(); refreshSubject.complete();
const [firstResponse, secondResponse] = await Promise.all([firstRequest, secondRequest]); const [firstResponse, secondResponse] = await Promise.all([firstRequest, secondRequest]);
@@ -179,7 +179,7 @@ describe('AuthInterceptorService', () => {
describe('isExcludedAuthRequest', () => { describe('isExcludedAuthRequest', () => {
const next = vi.fn((request: HttpRequest<unknown>) => 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 () => { it('excludes /api/v1/auth/login', async () => {
@@ -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));
@@ -1,9 +1,9 @@
import {HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http'; import { HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import {inject} from '@angular/core'; import { inject } from '@angular/core';
import {catchError, filter, switchMap, take} from 'rxjs/operators'; import { catchError, filter, switchMap, take } from 'rxjs/operators';
import {BehaviorSubject, Observable, throwError, defer} from 'rxjs'; import { BehaviorSubject, Observable, throwError, defer } from 'rxjs';
import {AuthService} from '../../shared/service/auth.service'; import { AuthService } from '../../shared/service/auth.service';
import {API_CONFIG} from '../config/api-config'; import { API_CONFIG } from '../config/api-config';
let isRefreshing = false; let isRefreshing = false;
const refreshTokenSubject = new BehaviorSubject<string | null>(null); 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/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;
}
}
}
@@ -1,27 +1,27 @@
import {AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, OnInit, signal, ViewChild} from '@angular/core'; import { AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, OnInit, signal, ViewChild } from '@angular/core';
import {computeGridColumns} from '../../../../shared/util/viewport.util'; import { computeGridColumns } from '../../../../shared/util/viewport.util';
import {ActivatedRoute, Router} from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import {NgClass, NgStyle} from '@angular/common'; import { NgClass, NgStyle } from '@angular/common';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs'; import { Tab, TabList, TabPanel, TabPanels, Tabs } from 'primeng/tabs';
import {ProgressSpinner} from 'primeng/progressspinner'; import { ProgressSpinner } from 'primeng/progressspinner';
import {Button} from 'primeng/button'; import { Button } from 'primeng/button';
import {Tag} from 'primeng/tag'; import { Tag } from 'primeng/tag';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; import { TranslocoDirective, TranslocoService } from '@jsverse/transloco';
import {CdkVirtualScrollViewport, CdkVirtualForOf} from '@angular/cdk/scrolling'; import { CdkVirtualScrollViewport, CdkVirtualForOf } from '@angular/cdk/scrolling';
import {CdkAutoSizeVirtualScroll} from '@angular/cdk-experimental/scrolling'; import { CdkAutoSizeVirtualScroll } from '@angular/cdk-experimental/scrolling';
import {MessageService} from 'primeng/api'; import { MessageService } from 'primeng/api';
import {Tooltip} from 'primeng/tooltip'; import { Tooltip } from 'primeng/tooltip';
import {AuthorService} from '../../service/author.service'; import { AuthorService } from '../../service/author.service';
import {AuthorDetails} from '../../model/author.model'; import { AuthorDetails } from '../../model/author.model';
import {BookService} from '../../../book/service/book.service'; import { BookService } from '../../../book/service/book.service';
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component'; import { BookCardComponent } from '../../../book/components/book-browser/book-card/book-card.component';
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service'; import { CoverScalePreferenceService } from '../../../book/components/book-browser/cover-scale-preference.service';
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service'; import { BookCardOverlayPreferenceService } from '../../../book/components/book-browser/book-card-overlay-preference.service';
import {UserService} from '../../../settings/user-management/user.service'; import { UserService } from '../../../settings/user-management/user.service';
import {AuthorMatchComponent} from '../author-match/author-match.component'; import { AuthorMatchComponent } from '../author-match/author-match.component';
import {AuthorEditorComponent} from '../author-editor/author-editor.component'; import { AuthorEditorComponent } from '../author-editor/author-editor.component';
import {PageTitleService} from '../../../../shared/service/page-title.service'; import { PageTitleService } from '../../../../shared/service/page-title.service';
import {chunk} from '../../../../shared/util/array.util'; import { chunk } from '../../../../shared/util/array.util';
@Component({ @Component({
selector: 'app-author-detail', selector: 'app-author-detail',
@@ -1,14 +1,14 @@
import {provideHttpClient} from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import {TestBed} from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import {Router} from '@angular/router'; import { Router } from '@angular/router';
import {of, throwError} from 'rxjs'; import { of, throwError } from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {API_CONFIG} from '../../core/config/api-config'; import { API_CONFIG } from '../../core/config/api-config';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service'; import { PostLoginInitializerService } from '../../core/services/post-login-initializer.service';
import {RxStompService} from '../websocket/rx-stomp.service'; import { RxStompService } from '../websocket/rx-stomp.service';
import {AuthService, websocketInitializer} from './auth.service'; import { AuthService, websocketInitializer } from './auth.service';
describe('AuthService', () => { describe('AuthService', () => {
const router = { const router = {
@@ -34,9 +34,9 @@ describe('AuthService', () => {
providers: [ providers: [
provideHttpClient(), provideHttpClient(),
provideHttpClientTesting(), provideHttpClientTesting(),
{provide: Router, useValue: router}, { provide: Router, useValue: router },
{provide: RxStompService, useValue: rxStompService}, { provide: RxStompService, useValue: rxStompService },
{provide: PostLoginInitializerService, useValue: postLoginInitializer}, { provide: PostLoginInitializerService, useValue: postLoginInitializer },
AuthService, AuthService,
] ]
}); });
@@ -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(() => {
@@ -58,12 +62,12 @@ describe('AuthService', () => {
}); });
it('logs in with internal credentials and initializes the authenticated session', () => { it('logs in with internal credentials and initializes the authenticated session', () => {
service.internalLogin({username: 'admin', password: 'secret'}).subscribe(); service.internalLogin({ username: 'admin', password: 'secret' }).subscribe();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/login`); const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/login`);
expect(request.request.method).toBe('POST'); expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({username: 'admin', password: 'secret'}); expect(request.request.body).toEqual({ username: 'admin', password: 'secret' });
request.flush({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'}); request.flush({ accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false' });
expect(service.getInternalAccessToken()).toBe('access'); expect(service.getInternalAccessToken()).toBe('access');
expect(service.getInternalRefreshToken()).toBe('refresh'); expect(service.getInternalRefreshToken()).toBe('refresh');
@@ -79,8 +83,8 @@ describe('AuthService', () => {
service.internalRefreshToken().subscribe(); service.internalRefreshToken().subscribe();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`); const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`);
expect(request.request.body).toEqual({refreshToken: 'refresh-token'}); expect(request.request.body).toEqual({ refreshToken: 'refresh-token' });
request.flush({accessToken: 'new-access', refreshToken: 'new-refresh'}); request.flush({ accessToken: 'new-access', refreshToken: 'new-refresh' });
expect(service.getInternalAccessToken()).toBe('new-access'); expect(service.getInternalAccessToken()).toBe('new-access');
expect(service.getInternalRefreshToken()).toBe('new-refresh'); expect(service.getInternalRefreshToken()).toBe('new-refresh');
@@ -91,7 +95,7 @@ describe('AuthService', () => {
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/remote`); const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/remote`);
expect(request.request.method).toBe('GET'); expect(request.request.method).toBe('GET');
request.flush({accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: 'false'}); request.flush({ accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: 'false' });
expect(service.getInternalAccessToken()).toBe('remote-access'); expect(service.getInternalAccessToken()).toBe('remote-access');
expect(rxStompService.activate).toHaveBeenCalledOnce(); expect(rxStompService.activate).toHaveBeenCalledOnce();
@@ -105,13 +109,13 @@ describe('AuthService', () => {
service.logout(); service.logout();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`); const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`);
request.flush({logoutUrl: null}); request.flush({ logoutUrl: null });
await Promise.resolve(); await Promise.resolve();
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 () => {
@@ -121,13 +125,13 @@ describe('AuthService', () => {
service.logout(); service.logout();
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`); const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`);
request.flush('boom', {status: 500, statusText: 'Server Error'}); request.flush('boom', { status: 500, statusText: 'Server Error' });
await Promise.resolve(); await Promise.resolve();
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', () => {
+40 -21
View File
@@ -1,11 +1,11 @@
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';
import {Router} from '@angular/router'; import { Router } from '@angular/router';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service'; import { PostLoginInitializerService } from '../../core/services/post-login-initializer.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@@ -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);
@@ -38,7 +41,7 @@ export class AuthService {
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> { internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
const refreshToken = this.getInternalRefreshToken(); const refreshToken = this.getInternalRefreshToken();
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe( return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, { refreshToken }).pipe(
tap((response) => { tap((response) => {
if (response.accessToken && response.refreshToken) { if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken); this.saveInternalTokens(response.accessToken, response.refreshToken);
@@ -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));