import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; import { inject } from '@angular/core'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; import { catchError, switchMap, tap, throwError } from 'rxjs'; import { CredentialService } from '../services/credential.service'; import { UiFocusService } from '../services/ui-focus.service'; export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { const url = req.url.split('?')[0]; const uiFocusService = inject(UiFocusService); const isPublicAuthRequest = req.method === 'POST' && (url.endsWith('/api/auth/v2/request-otk') || url.endsWith('/api/auth/v2/login') || url.endsWith('/api/auth/v2/access') || url.endsWith('/api/auth/v2/refresh')); if (isPublicAuthRequest || url.endsWith('/institutions/autocomplete')) { return next(req); } const credentialService = inject(CredentialService); const router = inject(Router); const snackBar = inject(MatSnackBar); const tokenProvider = credentialService.getBearerToken(); const isLogoutRequest = url.endsWith('/api/auth/v2/logout'); return tokenProvider.pipe( switchMap((response) => { if (response == undefined) { credentialService.clearLocalAuthState(); snackBar.open( 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', 'OK', { duration: 7000 }, ); void router.navigate(['/login']); return throwError( () => new HttpErrorResponse({ status: 403, statusText: 'Forbidden' }), ); } const authorizedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + response), }); return next(authorizedRequest).pipe( catchError((error: HttpErrorResponse) => { if (error.status === 401 && !isLogoutRequest) { return credentialService.handleUnauthorized().pipe( tap((result) => { uiFocusService.blurActiveElement(); if (result === 'stopped-impersonating') { snackBar.open( 'Die Impersonation wurde beendet, weil die Sitzung nicht mehr gültig ist.', 'OK', { duration: 7000 }, ); void router.navigate(['/accounts']); } else if (result === 'logged-out') { snackBar.open( 'Ihre Sitzung ist abgelaufen oder wurde beendet. Bitte melden Sie sich erneut an.', 'OK', { duration: 7000 }, ); void router.navigate(['/login']); } }), switchMap(() => throwError(() => error)), ); } return throwError(() => error); }), ); }), ); };