Project

General

Profile

1 61381 k.triantaf
import {Injectable} from "@angular/core";
2
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
3
import {Observable, throwError, TimeoutError} from "rxjs";
4
import {catchError} from "rxjs/operators";
5
import {Session} from "./login/utils/helper.class";
6
import {Router} from "@angular/router";
7
import {LoginErrorCodes} from "./login/utils/guardHelper.class";
8
import {properties} from "../../environments/environment";
9
import {isArray} from "util";
10
11
@Injectable()
12
export class ErrorInterceptorService implements HttpInterceptor {
13
14
  private static UNAUTHORIZED_WHITELIST = [properties.userInfoUrl, properties.orcidAPIURL, properties.registryUrl + 'verification/'];
15
16
  constructor(private router: Router) {
17
  }
18
19
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
20
    return next.handle(req).pipe(catchError(err => {
21
      if(err instanceof TimeoutError) {
22
        console.error(req.url, "Timeout");
23
      }
24
      if ((err.status === 0 && properties.registryUrl && this.isService(req, properties.registryUrl) && req.method !== 'GET') ||
25
        (err.status === 401 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST))) {
26
        this.logOut();
27
      } else if(err.status === 403 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST)) {
28
        this.unauthorized();
29
      }
30
      return throwError(err);
31
    }));
32
  }
33
34
  isService(req: HttpRequest<any>, service: string | string[]):boolean {
35
    if(isArray(service)) {
36
      return !!service.find(element => req.url.indexOf(element) !== -1);
37
    } else {
38
      return req.url.indexOf(service) !== -1;
39
    }
40
  }
41
42
  logOut() {
43
    Session.removeUser();
44
    this.router.navigate(['/user-info'], {
45
      queryParams: {
46
        'errorCode': LoginErrorCodes.NOT_LOGIN,
47
        'redirectUrl': this.router.url
48
      }
49
    });
50
  }
51
52
  unauthorized() {
53
    this.router.navigate(['/user-info'], {
54
      queryParams: {
55
        'errorCode': LoginErrorCodes.NOT_AUTHORIZED,
56
        'redirectUrl': this.router.url
57
      }
58
    });
59
  }
60
}