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> { console.log('Welcome to interceptor:', request.url); console.log('IsAuth?', request.url.includes('/auth/apiToken')); if (!request.url.includes('/auth/apiToken')) { console.log(this.auth$.expirationTime.format(), moment.utc().format()); if (this.auth$.expirationTime.isBefore(moment.utc())) { console.log('Need to refresh token'); return this.auth$.getAPITokenObservable().pipe( mergeMap(() => { console.log('New token is ready'); 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 { console.log('TOken is fine'); return next.handle(request.clone({ headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`), })); } } else { return next.handle(request); } } }