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