diff --git a/frontend/src/app/core/errors/global-error-handler.ts b/frontend/src/app/core/errors/global-error-handler.ts new file mode 100644 index 000000000..600e769ba --- /dev/null +++ b/frontend/src/app/core/errors/global-error-handler.ts @@ -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); + } + } +} diff --git a/frontend/src/app/core/security/auth-interceptor.service.spec.ts b/frontend/src/app/core/security/auth-interceptor.service.spec.ts index 3ad49bd61..b319218ca 100644 --- a/frontend/src/app/core/security/auth-interceptor.service.spec.ts +++ b/frontend/src/app/core/security/auth-interceptor.service.spec.ts @@ -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) => of(new HttpResponse({status: 200, body: request.headers.get('Authorization')}))); + const next = vi.fn((request: HttpRequest) => 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) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')}))); + const next = vi.fn((request: HttpRequest) => 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) => of(new HttpResponse({status: 200, body: request.headers.has('Authorization')}))); + const next = vi.fn((request: HttpRequest) => 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) => { 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) => { 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) => { 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) => - 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).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).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)); diff --git a/frontend/src/app/core/security/auth-interceptor.service.ts b/frontend/src/app/core/security/auth-interceptor.service.ts index c7c8fbe4f..b14b760da 100644 --- a/frontend/src/app/core/security/auth-interceptor.service.ts +++ b/frontend/src/app/core/security/auth-interceptor.service.ts @@ -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(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}`); diff --git a/frontend/src/app/core/services/pwa-update.service.ts b/frontend/src/app/core/services/pwa-update.service.ts new file mode 100644 index 000000000..6e1b79497 --- /dev/null +++ b/frontend/src/app/core/services/pwa-update.service.ts @@ -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; + } + } +} diff --git a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts index 15f637764..1fcb26e93 100644 --- a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts +++ b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts @@ -1,27 +1,27 @@ -import {AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, OnInit, signal, ViewChild} from '@angular/core'; -import {computeGridColumns} from '../../../../shared/util/viewport.util'; -import {ActivatedRoute, Router} from '@angular/router'; -import {NgClass, NgStyle} from '@angular/common'; -import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs'; -import {ProgressSpinner} from 'primeng/progressspinner'; -import {Button} from 'primeng/button'; -import {Tag} from 'primeng/tag'; -import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; -import {CdkVirtualScrollViewport, CdkVirtualForOf} from '@angular/cdk/scrolling'; -import {CdkAutoSizeVirtualScroll} from '@angular/cdk-experimental/scrolling'; -import {MessageService} from 'primeng/api'; -import {Tooltip} from 'primeng/tooltip'; -import {AuthorService} from '../../service/author.service'; -import {AuthorDetails} from '../../model/author.model'; -import {BookService} from '../../../book/service/book.service'; -import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component'; -import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service'; -import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service'; -import {UserService} from '../../../settings/user-management/user.service'; -import {AuthorMatchComponent} from '../author-match/author-match.component'; -import {AuthorEditorComponent} from '../author-editor/author-editor.component'; -import {PageTitleService} from '../../../../shared/service/page-title.service'; -import {chunk} from '../../../../shared/util/array.util'; +import { AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, OnInit, signal, ViewChild } from '@angular/core'; +import { computeGridColumns } from '../../../../shared/util/viewport.util'; +import { ActivatedRoute, Router } from '@angular/router'; +import { NgClass, NgStyle } from '@angular/common'; +import { Tab, TabList, TabPanel, TabPanels, Tabs } from 'primeng/tabs'; +import { ProgressSpinner } from 'primeng/progressspinner'; +import { Button } from 'primeng/button'; +import { Tag } from 'primeng/tag'; +import { TranslocoDirective, TranslocoService } from '@jsverse/transloco'; +import { CdkVirtualScrollViewport, CdkVirtualForOf } from '@angular/cdk/scrolling'; +import { CdkAutoSizeVirtualScroll } from '@angular/cdk-experimental/scrolling'; +import { MessageService } from 'primeng/api'; +import { Tooltip } from 'primeng/tooltip'; +import { AuthorService } from '../../service/author.service'; +import { AuthorDetails } from '../../model/author.model'; +import { BookService } from '../../../book/service/book.service'; +import { BookCardComponent } from '../../../book/components/book-browser/book-card/book-card.component'; +import { CoverScalePreferenceService } from '../../../book/components/book-browser/cover-scale-preference.service'; +import { BookCardOverlayPreferenceService } from '../../../book/components/book-browser/book-card-overlay-preference.service'; +import { UserService } from '../../../settings/user-management/user.service'; +import { AuthorMatchComponent } from '../author-match/author-match.component'; +import { AuthorEditorComponent } from '../author-editor/author-editor.component'; +import { PageTitleService } from '../../../../shared/service/page-title.service'; +import { chunk } from '../../../../shared/util/array.util'; @Component({ selector: 'app-author-detail', diff --git a/frontend/src/app/shared/service/auth.service.spec.ts b/frontend/src/app/shared/service/auth.service.spec.ts index db265dfa6..24682125b 100644 --- a/frontend/src/app/shared/service/auth.service.spec.ts +++ b/frontend/src/app/shared/service/auth.service.spec.ts @@ -1,14 +1,14 @@ -import {provideHttpClient} from '@angular/common/http'; -import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; -import {TestBed} from '@angular/core/testing'; -import {Router} from '@angular/router'; -import {of, throwError} from 'rxjs'; -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; +import { of, throwError } from 'rxjs'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import {API_CONFIG} from '../../core/config/api-config'; -import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service'; -import {RxStompService} from '../websocket/rx-stomp.service'; -import {AuthService, websocketInitializer} from './auth.service'; +import { API_CONFIG } from '../../core/config/api-config'; +import { PostLoginInitializerService } from '../../core/services/post-login-initializer.service'; +import { RxStompService } from '../websocket/rx-stomp.service'; +import { AuthService, websocketInitializer } from './auth.service'; describe('AuthService', () => { const router = { @@ -34,9 +34,9 @@ describe('AuthService', () => { providers: [ provideHttpClient(), provideHttpClientTesting(), - {provide: Router, useValue: router}, - {provide: RxStompService, useValue: rxStompService}, - {provide: PostLoginInitializerService, useValue: postLoginInitializer}, + { provide: Router, useValue: router }, + { provide: RxStompService, useValue: rxStompService }, + { provide: PostLoginInitializerService, useValue: postLoginInitializer }, AuthService, ] }); @@ -49,6 +49,10 @@ describe('AuthService', () => { service = TestBed.inject(AuthService); 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(() => { @@ -58,12 +62,12 @@ describe('AuthService', () => { }); 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`); expect(request.request.method).toBe('POST'); - expect(request.request.body).toEqual({username: 'admin', password: 'secret'}); - request.flush({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'}); + expect(request.request.body).toEqual({ username: 'admin', password: 'secret' }); + request.flush({ accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false' }); expect(service.getInternalAccessToken()).toBe('access'); expect(service.getInternalRefreshToken()).toBe('refresh'); @@ -79,8 +83,8 @@ describe('AuthService', () => { service.internalRefreshToken().subscribe(); const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/refresh`); - expect(request.request.body).toEqual({refreshToken: 'refresh-token'}); - request.flush({accessToken: 'new-access', refreshToken: 'new-refresh'}); + expect(request.request.body).toEqual({ refreshToken: 'refresh-token' }); + request.flush({ accessToken: 'new-access', refreshToken: 'new-refresh' }); expect(service.getInternalAccessToken()).toBe('new-access'); expect(service.getInternalRefreshToken()).toBe('new-refresh'); @@ -91,7 +95,7 @@ describe('AuthService', () => { const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/remote`); 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(rxStompService.activate).toHaveBeenCalledOnce(); @@ -105,13 +109,13 @@ describe('AuthService', () => { service.logout(); const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/logout`); - request.flush({logoutUrl: null}); + request.flush({ logoutUrl: null }); await Promise.resolve(); expect(service.token()).toBeNull(); 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 () => { @@ -121,13 +125,13 @@ describe('AuthService', () => { service.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(); expect(service.token()).toBeNull(); 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', () => { @@ -138,9 +142,7 @@ describe('AuthService', () => { expect(service.token()).toBeNull(); expect(rxStompService.deactivate).toHaveBeenCalledOnce(); - expect(router.navigate).toHaveBeenCalledWith(['/login'], { - queryParams: {reason: 'session_revoked'}, - }); + expect((service as unknown as { redirectTo: AuthService['redirectTo'] }).redirectTo).toHaveBeenCalledWith('/login?reason=session_revoked', true); }); it('clears the session when the login page is opened', () => { diff --git a/frontend/src/app/shared/service/auth.service.ts b/frontend/src/app/shared/service/auth.service.ts index b12c30db7..9d2f82841 100644 --- a/frontend/src/app/shared/service/auth.service.ts +++ b/frontend/src/app/shared/service/auth.service.ts @@ -1,11 +1,11 @@ -import {computed, inject, Injectable, Injector, signal} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {Observable, tap} from 'rxjs'; -import {RxStompService} from '../websocket/rx-stomp.service'; -import {API_CONFIG} from '../../core/config/api-config'; -import {createRxStompConfig} from '../websocket/rx-stomp.config'; -import {Router} from '@angular/router'; -import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service'; +import { computed, inject, Injectable, Injector, signal } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable, tap, finalize } from 'rxjs'; +import { RxStompService } from '../websocket/rx-stomp.service'; +import { API_CONFIG } from '../../core/config/api-config'; +import { createRxStompConfig } from '../websocket/rx-stomp.config'; +import { Router } from '@angular/router'; +import { PostLoginInitializerService } from '../../core/services/post-login-initializer.service'; @Injectable({ providedIn: 'root', @@ -14,7 +14,10 @@ export class AuthService { private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`; 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 injector = inject(Injector); @@ -38,7 +41,7 @@ export class AuthService { internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> { 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) => { if (response.accessToken && response.refreshToken) { this.saveInternalTokens(response.accessToken, response.refreshToken); @@ -74,26 +77,42 @@ export class AuthService { } logout(): void { + if (this._logoutInProgress()) return; + this._logoutInProgress.set(true); + const refreshToken = this.getInternalRefreshToken(); - this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, {refreshToken}).subscribe({ - next: (response) => { - if (response.logoutUrl) { - window.location.href = response.logoutUrl; - } else { - this.clearSession(); - this.router.navigate(['/login']).then(() => window.location.reload()); + this.clearSession(); + + this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, { refreshToken }) + .pipe(finalize(() => { + this._logoutInProgress.set(false); + })) + .subscribe({ + next: (response) => { + if (response.logoutUrl) { + this.redirectTo(response.logoutUrl, true); + } else { + this.redirectTo('/login', true); + } + }, + error: () => { + this.redirectTo('/login', true); } - }, - error: () => { - this.clearSession(); - this.router.navigate(['/login']).then(() => window.location.reload()); - } - }); + }); } forceLogout(reason: string): void { + this._logoutInProgress.set(true); 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 { @@ -104,7 +123,7 @@ export class AuthService { localStorage.removeItem('accessToken_Internal'); localStorage.removeItem('refreshToken_Internal'); this.token.set(null); - this.postLoginInitialized = false; + this._postLoginInitialized.set(false); this.getRxStompService().deactivate(); } @@ -124,14 +143,14 @@ export class AuthService { stompService.updateConfig(config); stompService.activate(); - if (!this.postLoginInitialized) { + if (!this._postLoginInitialized()) { this.handleSuccessfulAuth(); } } private handleSuccessfulAuth() { - if (this.postLoginInitialized) return; - this.postLoginInitialized = true; + if (this._postLoginInitialized()) return; + this._postLoginInitialized.set(true); this.postLoginInitializer.initialize().subscribe({ next: () => console.log('AuthService: Post-login initialization completed'), error: (err) => console.error('AuthService: Post-login initialization failed:', err) diff --git a/frontend/src/main.ts b/frontend/src/main.ts index d52c600ce..99747ff3b 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -1,4 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { ErrorHandler, inject, isDevMode, provideAppInitializer, provideZonelessChangeDetection } from '@angular/core'; import { DialogService } from 'primeng/dynamicdialog'; import { ConfirmationService, MessageService } from 'primeng/api'; 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 { AuthInterceptorService } from './app/core/security/auth-interceptor.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 { StartupService } from './app/shared/service/startup.service'; import { provideCharts, withDefaultRegisterables } from 'ng2-charts'; @@ -80,6 +82,10 @@ bootstrapApplication(AppComponent, { }), provideServiceWorker('ngsw-worker.js', { enabled: !isDevMode(), registrationStrategy: 'registerWhenStable:30000' + }), + { provide: ErrorHandler, useClass: GlobalErrorHandler }, + provideAppInitializer(() => { + inject(PwaUpdateService); }) ] }).catch(err => console.error(err));