import {Injectable} from '@angular/core'; import {HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http'; import {Observable} from 'rxjs'; import {tap} from 'rxjs/operators'; import {SessionService} from '../service/session.service'; @Injectable() export class AuthHttpInterceptor implements HttpInterceptor { constructor(private ss: SessionService) { } intercept(req: HttpRequest, next: HttpHandler): Observable> { let h = req.headers; if (this.ss.loggedIn.hasValidSession()) { h = h.set('Biukop-Session', this.ss.loggedIn.session); } if (this.ss.loggedIn.hasValidMachineId()) { h = h.set('Biukop-Mid', this.ss.loggedIn.machineId); } const authReq = req.clone({ headers: h, withCredentials: true }); return next.handle(authReq).pipe( tap(event => { // console.log(event); if (event.type === HttpEventType.Response){ const bs = event.headers.get('biukop-session'); if (bs !== undefined){ if ( this.ss.loggedIn.session !== bs ){ this.ss.loggedIn.session = bs; this.ss.saveSessionInfo(); console.log('switch session:' , bs); } } } }) ); } }