diff --git a/interfaces/IBF-dashboard/src/app/app.module.ts b/interfaces/IBF-dashboard/src/app/app.module.ts index 8d42aca05..7fa6464de 100644 --- a/interfaces/IBF-dashboard/src/app/app.module.ts +++ b/interfaces/IBF-dashboard/src/app/app.module.ts @@ -14,6 +14,7 @@ import { LoaderInterceptorService } from 'src/app/services/loader.interceptor.se import { environment } from 'src/environments/environment'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; +import { AuthInterceptorService } from './services/auth.interceptor.service'; export function createTranslateLoader(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/', '.json'); @@ -49,6 +50,11 @@ export function createTranslateLoader(http: HttpClient) { useClass: LoaderInterceptorService, multi: true, }, + { + provide: HTTP_INTERCEPTORS, + useClass: AuthInterceptorService, + multi: true, + }, ], bootstrap: [AppComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA], diff --git a/interfaces/IBF-dashboard/src/app/services/auth.interceptor.service.ts b/interfaces/IBF-dashboard/src/app/services/auth.interceptor.service.ts new file mode 100644 index 000000000..7de498faa --- /dev/null +++ b/interfaces/IBF-dashboard/src/app/services/auth.interceptor.service.ts @@ -0,0 +1,51 @@ +import { + HttpErrorResponse, + HttpEvent, + HttpHandler, + HttpInterceptor, + HttpRequest, + HttpResponse, +} from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs'; +import { tap } from 'rxjs/operators'; +import { environment } from 'src/environments/environment'; +import { AuthService } from '../auth/auth.service'; + +@Injectable({ providedIn: 'root' }) +export class AuthInterceptorService implements HttpInterceptor { + constructor(private authService: AuthService) {} + + intercept( + request: HttpRequest, + next: HttpHandler, + ): Observable> { + return next.handle(request).pipe( + tap( + (event) => this.handleResponse(event), + (error) => this.handleError(error), + ), + ); + } + + private handleResponse(event: HttpEvent): void { + if (event instanceof HttpResponse) { + const isCountryRequest = + event.url?.startsWith( + `${environment.apiUrl}/country?countryCodesISO3=`, + ) ?? false; + const isEmptyResponse = + Array.isArray(event.body) && event.body.length === 0; + + if (isCountryRequest && isEmptyResponse) { + this.authService.logout(); + } + } + } + + private handleError(error: unknown): void { + if (error instanceof HttpErrorResponse && error.status === 401) { + this.authService.logout(); + } + } +}