import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { AuthService } from '../auth/auth.service'; import { EMPTY, Observable } from 'rxjs'; import moment from 'moment'; import { catchError, mergeMap } from 'rxjs/operators'; import { NotificationsService } from '../services/notifications.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor( private auth$: AuthService, private notifications$: NotificationsService ) { } intercept(request: HttpRequest, next: HttpHandler): Observable> { if (!request.url.includes('/auth/apiToken')) { if (this.auth$.expirationTime.isBefore(moment.utc())) { return this.auth$.getAPITokenObservable().pipe( mergeMap(() => { return next.handle(request.clone({ headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`), })); }), catchError(() => { this.notifications$.add({ text: "User session is expired and unable to restore. Please restart the app.", btn: "Restart", action: () => { window.location.reload(); }, duration: 5000, }); return EMPTY; }) ); } else { return next.handle(request.clone({ headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`), })); } } else { return next.handle(request); } } }