1
|
import { Injectable } from '@angular/core';
|
2
|
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
|
3
|
import { Router } from '@angular/router';
|
4
|
import { Observable, throwError } from 'rxjs';
|
5
|
import { tap } from 'rxjs/operators';
|
6
|
|
7
|
@Injectable()
|
8
|
export class AuthenticationInterceptor implements HttpInterceptor {
|
9
|
|
10
|
constructor(private router: Router) {}
|
11
|
|
12
|
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
13
|
|
14
|
return next.handle(request).pipe(
|
15
|
tap( (event: HttpEvent<any>) => {
|
16
|
if (event instanceof HttpResponse) {
|
17
|
// do stuff with response if you want
|
18
|
}
|
19
|
},
|
20
|
(err: any) => {
|
21
|
if (err instanceof HttpErrorResponse) {
|
22
|
console.log(err);
|
23
|
if (err.status === 403) {
|
24
|
console.log('Unauthorised!!', err);
|
25
|
this.router.navigateByUrl('/403-forbidden', { skipLocationChange: true });
|
26
|
} else {
|
27
|
this.handleError(err);
|
28
|
}
|
29
|
}
|
30
|
}
|
31
|
)
|
32
|
);
|
33
|
}
|
34
|
|
35
|
/*handleError function as provided by angular.io (copied on 22/10/2018)*/
|
36
|
private handleError(error: HttpErrorResponse) {
|
37
|
if (error.error instanceof ErrorEvent) {
|
38
|
// A client-side or network error occurred. Handle it accordingly.
|
39
|
console.error('An error occurred:', error.error.message);
|
40
|
} else {
|
41
|
// The backend returned an unsuccessful response code.
|
42
|
// The response body may contain clues as to what went wrong,
|
43
|
console.error(
|
44
|
`Backend returned code ${error.status}, ` +
|
45
|
`body was: ${error.error}`);
|
46
|
}
|
47
|
// return an observable with a user-facing error message
|
48
|
return throwError(
|
49
|
'Something bad happened; please try again later.');
|
50
|
}
|
51
|
}
|