From f8e1ce6a7bdd2c142276a19958b17f8fab087083 Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com> Date: Wed, 8 Jan 2025 17:10:34 +0000 Subject: [PATCH] csrf fixes (#2647) # Description Please provide a summary of the changes, including relevant motivation and context. Closes #(issue_number) ## Checklist - [ ] I have read the [Contribution Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md) - [ ] I have performed a self-review of my own code - [ ] I have attached images of the change if it is UI based - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] If my code has heavily changed functionality I have updated relevant docs on [Stirling-PDFs doc repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/) - [ ] My changes generate no new warnings - [ ] I have read the section [Add New Translation Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/HowToAddNewLanguage.md#add-new-translation-tags) (for new translation tags only) --- src/main/resources/static/js/csrf.js | 37 +++++++++++++++++++ .../resources/templates/fragments/common.html | 1 + 2 files changed, 38 insertions(+) create mode 100644 src/main/resources/static/js/csrf.js diff --git a/src/main/resources/static/js/csrf.js b/src/main/resources/static/js/csrf.js new file mode 100644 index 000000000..2dc1c0ca2 --- /dev/null +++ b/src/main/resources/static/js/csrf.js @@ -0,0 +1,37 @@ +document.addEventListener('DOMContentLoaded', function() { + // Get CSRF token from cookie + const getCsrfToken = () => { + return document.cookie + .split('; ') + .find(row => row.startsWith('XSRF-TOKEN=')) + ?.split('=')[1]; + }; + + // Function to decode the URI-encoded cookie value + const decodeCsrfToken = (token) => { + if (token) { + return decodeURIComponent(token); + } + return null; + }; + + // Find all forms and add CSRF token + const forms = document.querySelectorAll('form'); + const csrfToken = decodeCsrfToken(getCsrfToken()); + + // Only proceed if we have a cookie-based token + if (csrfToken) { + forms.forEach(form => { + // Only now remove existing CSRF input fields since we have a new token + const existingCsrfInputs = form.querySelectorAll('input[name="_csrf"]'); + existingCsrfInputs.forEach(input => input.remove()); + + // Create and add new CSRF input field + const csrfInput = document.createElement('input'); + csrfInput.type = 'hidden'; + csrfInput.name = '_csrf'; + csrfInput.value = csrfToken; + form.appendChild(csrfInput); + }); + } +}); \ No newline at end of file diff --git a/src/main/resources/templates/fragments/common.html b/src/main/resources/templates/fragments/common.html index 1cd908a69..a6099f5a1 100644 --- a/src/main/resources/templates/fragments/common.html +++ b/src/main/resources/templates/fragments/common.html @@ -73,6 +73,7 @@ +