only call if cookie exists

This commit is contained in:
Anthony Stirling
2025-01-08 17:06:44 +00:00
parent 198fc1ced3
commit e49ca245e5

View File

@@ -17,19 +17,21 @@ document.addEventListener('DOMContentLoaded', function() {
// Find all forms and add CSRF token // Find all forms and add CSRF token
const forms = document.querySelectorAll('form'); const forms = document.querySelectorAll('form');
const csrfToken = decodeCsrfToken(getCsrfToken());
// Only proceed if we have a cookie-based token
if (csrfToken) {
forms.forEach(form => { forms.forEach(form => {
// Remove any existing CSRF input fields // Only now remove existing CSRF input fields since we have a new token
const existingCsrfInputs = form.querySelectorAll('input[name="_csrf"]'); const existingCsrfInputs = form.querySelectorAll('input[name="_csrf"]');
existingCsrfInputs.forEach(input => input.remove()); existingCsrfInputs.forEach(input => input.remove());
// Create and add new CSRF input field // Create and add new CSRF input field
const csrfToken = decodeCsrfToken(getCsrfToken());
if (csrfToken) {
const csrfInput = document.createElement('input'); const csrfInput = document.createElement('input');
csrfInput.type = 'hidden'; csrfInput.type = 'hidden';
csrfInput.name = '_csrf'; csrfInput.name = '_csrf';
csrfInput.value = csrfToken; csrfInput.value = csrfToken;
form.appendChild(csrfInput); form.appendChild(csrfInput);
});
} }
}); });
});