lion/packages/ajax/src/interceptors/xsrfHeader.js
Goffert van Gool 73d4e222f6
Update public API of ajax & refactor package (#1371)
feat(ajax): align / break public API

Co-authored-by: Ahmet Yesil <yesil.ahmet@ing.com>
2021-05-12 15:21:18 +02:00

34 lines
1.1 KiB
JavaScript

import '../typedef.js';
/**
* @param {string} name the cookie name
* @param {Document | { cookie: string }} _document overwriteable for testing
* @returns {string | null}
*/
export function getCookie(name, _document = document) {
const match = _document.cookie.match(new RegExp(`(^|;\\s*)(${name})=([^;]*)`));
return match ? decodeURIComponent(match[3]) : null;
}
/**
* Creates a request transformer that adds a XSRF header for protecting
* against cross-site request forgery.
* @param {string} cookieName the cookie name
* @param {string} headerName the header name
* @param {Document | { cookie: string }} _document overwriteable for testing
* @returns {RequestInterceptor}
*/
export function createXsrfRequestInterceptor(cookieName, headerName, _document = document) {
/**
* @type {RequestInterceptor}
*/
async function xsrfRequestInterceptor(request) {
const xsrfToken = getCookie(cookieName, _document);
if (xsrfToken) {
request.headers.set(headerName, xsrfToken);
}
return request;
}
return xsrfRequestInterceptor;
}