paperless-ngx/src-ui/src/app/services/auth.interceptor.ts

38 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-10-27 01:10:18 +01:00
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
2020-10-29 14:35:36 +01:00
HttpInterceptor,
HttpErrorResponse
2020-10-27 01:10:18 +01:00
} from '@angular/common/http';
2020-10-29 14:35:36 +01:00
import { Observable, throwError } from 'rxjs';
2020-10-27 01:10:18 +01:00
import { AuthService } from './auth.service';
2020-10-29 14:35:36 +01:00
import { catchError } from 'rxjs/operators';
import { Toast, ToastService } from './toast.service';
2020-10-27 01:10:18 +01:00
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
2020-10-29 14:35:36 +01:00
constructor(private authService: AuthService, private toastService: ToastService) {}
2020-10-27 01:10:18 +01:00
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
if (this.authService.isAuthenticated()) {
request = request.clone({
setHeaders: {
Authorization: 'Token ' + this.authService.getToken()
}
});
}
2020-10-29 14:35:36 +01:00
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)
})
);
2020-10-27 01:10:18 +01:00
}
}