From 3d61373431d66cf006009a600d076ca0c227a203 Mon Sep 17 00:00:00 2001 From: Sam Dudley Date: Tue, 18 Feb 2025 14:25:55 +0000 Subject: [PATCH] fix csrf --- core/templates/base_generic.html | 6 +----- front_end/src/Util.js | 32 +++++++++++--------------------- 2 files changed, 12 insertions(+), 26 deletions(-) diff --git a/core/templates/base_generic.html b/core/templates/base_generic.html index 6fc4a37e0..068113cc0 100644 --- a/core/templates/base_generic.html +++ b/core/templates/base_generic.html @@ -263,11 +263,7 @@ import FeatureFlags from "{% static 'core/js/feature-flags.js' %}"; window.GOVUKFrontend.initAll(); - - function getCsrfToken() { - return "{{ csrf_token }}"; - } - + window.CSRF_TOKEN = "{{ csrf_token }}"; window.FEATURES = FeatureFlags("fft:features"); {% block scripts %} diff --git a/front_end/src/Util.js b/front_end/src/Util.js index cc31ec124..98d85bc69 100644 --- a/front_end/src/Util.js +++ b/front_end/src/Util.js @@ -78,37 +78,27 @@ export async function getData(url) { * * @param {string} url - URL to POST data to. * @param {object} data - Payload to send. + * @param {?string} content_type - Content-Type header for the body. * @returns {PostDataResponse} */ -export async function postData(url = "", data = {}) { - // NOTE: This doesn't work! We set `CSRF_COOKIE_HTTPONLY = True` so the code which - // uses this function include the CSRF token as part of the submitted form data by - // pulling it from DOM. - var csrftoken = getCookie("csrftoken"); - - /* - const defaults = { - 'method': 'POST', - 'credentials': 'include', - 'headers': new Headers({ - 'X-CSRFToken': csrftoken, - 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', - 'X-Requested-With': 'XMLHttpRequest' - }) - */ +export async function postData(url = "", data = {}, content_type = null) { + const csrftoken = window.CSRF_TOKEN; + + if (!content_type) { + content_type = "application/x-www-form-urlencoded" + ? data instanceof FormData + : "application/json"; + } // Default options are marked with * const response = await fetch(url, { method: "POST", // *GET, POST, PUT, DELETE, etc. - mode: "cors", // no-cors, *cors, same-origin + mode: "same-origin", // no-cors, *cors, same-origin cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached credentials: "same-origin", // include, *same-origin, omit headers: { - //'Content-Type': 'application/json', - //'Content-Type': 'multipart/formdata', "X-CSRFToken": csrftoken, - //'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', - "X-Requested-With": "XMLHttpRequest", + "Content-Type": content_type, }, redirect: "follow", // manual, *follow, error referrer: "no-referrer", // no-referrer, *client