import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpXsrfTokenExtractor
} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {TokenConstants} from "../../security/TokenConstants";

@Injectable()
export class AbsoluteUrlCsrfInterceptor implements HttpInterceptor {

  constructor(private extractor: HttpXsrfTokenExtractor) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (req.method === 'GET' || req.method === 'HEAD') {
      return next.handle(req);
    }
    let token = this.extractor.getToken();
    let headerName = TokenConstants.CSRF_HEADER_NAME;

    if (token != null && !req.headers.has(headerName)) {
      let headers = {};
      headers[headerName] = token;
      req = req.clone({setHeaders: headers});
    }
    return next.handle(req);
  }
}
