angular/projects/researchdatabox/portal-ng-common/src/lib/csrf.interceptor.ts
Interceptor for CSRF, etc.
Author: Shilo Banihit
Properties |
|
Methods |
constructor()
|
intercept | |||||||||
intercept(req: HttpRequest
|
|||||||||
Parameters :
Returns :
any
|
Private headers |
Type : any
|
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpContextToken } from '@angular/common/http';
import { get as _get, isEmpty as _isEmpty, set as _set, clone as _clone } from 'lodash-es';
export const RB_HTTP_INTERCEPTOR_AUTH_CSRF = new HttpContextToken(() => '');
/**
* Interceptor for CSRF, etc.
*
* Author: <a href='https://github.com/shilob' target='_blank'>Shilo Banihit</a>
*/
@Injectable()
export class CsrfInterceptor implements HttpInterceptor {
private headers: any;
constructor() {
this.headers = {
'X-Source': 'jsclient',
'Content-Type': 'application/json;charset=utf-8'
};
}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const headers = _clone(this.headers);
const csrfToken = req.context.get(RB_HTTP_INTERCEPTOR_AUTH_CSRF);
if (!_isEmpty(csrfToken) && _isEmpty(_get(this.headers, 'X-CSRF-Token'))) {
_set(headers, 'X-CSRF-Token', csrfToken);
}
const authReq = req.clone({
setHeaders: headers
});
// send cloned request with header to the next handler.
return next.handle(authReq);
}
}