Skip to content

Commit

Permalink
Merge pull request #1510 from rodekruis/fix.auth-interceptor
Browse files Browse the repository at this point in the history
fix: use auth interceptor
  • Loading branch information
gulfaraz authored Jul 12, 2024
2 parents 774f28c + 24c3d90 commit e36ab1c
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
6 changes: 6 additions & 0 deletions interfaces/IBF-dashboard/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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],
Expand Down
Original file line number Diff line number Diff line change
@@ -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<unknown>,
next: HttpHandler,
): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
tap(
(event) => this.handleResponse(event),
(error) => this.handleError(error),
),
);
}

private handleResponse(event: HttpEvent<unknown>): 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();
}
}
}

0 comments on commit e36ab1c

Please sign in to comment.