paperless-ngx/src-ui/src/app/services/auth.interceptor.ts
2020-10-29 14:35:36 +01:00

38 lines
1.1 KiB
TypeScript

import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { AuthService } from './auth.service';
import { catchError } from 'rxjs/operators';
import { Toast, ToastService } from './toast.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private toastService: ToastService) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
if (this.authService.isAuthenticated()) {
request = request.clone({
setHeaders: {
Authorization: 'Token ' + this.authService.getToken()
}
});
}
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status == 401 && this.authService.isAuthenticated()) {
this.authService.logout()
this.toastService.showToast(Toast.makeError("Your session has expired. Please log in again."))
}
return throwError(error)
})
);
}
}