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

@Injectable()
export class CSRFProtectInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


    // Set X-Requested-With header
    // Such a header cannot be set by an CSRF request,
    // WikiSpeech server will check the header and reject the request if it is not set
    // See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Verifying_Same_Origin_with_Standard_Headers
    // Chapter: "Protecting REST Services: Use of Custom Request Headers"
    // (Request is immutable, it needs to be cloned)
    const restReq = req.clone({headers: req.headers.set('X-Requested-With', 'XMLHttpRequest')});
    // Pass the cloned request
    return next.handle(restReq);
  }
}
