Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ document.addEventListener('turbo:submit-end', function (event) {
});

export function generateCsrfToken (formElement) {
const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
const csrfField = getCsrfField(formElement);

if (!csrfField) {
return;
Expand All @@ -46,7 +46,7 @@ export function generateCsrfToken (formElement) {

export function generateCsrfHeaders (formElement) {
const headers = {};
const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
const csrfField = getCsrfField(formElement);

if (!csrfField) {
return headers;
Expand All @@ -62,7 +62,7 @@ export function generateCsrfHeaders (formElement) {
}

export function removeCsrfToken (formElement) {
const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
const csrfField = getCsrfField(formElement);

if (!csrfField) {
return;
Expand All @@ -77,5 +77,17 @@ export function removeCsrfToken (formElement) {
}
}

function getCsrfField (formElement)
{
// Input element is placed inside the form
const qSel = 'input[data-controller="csrf-protection"], input[name="_csrf_token"]';
const csrfField = formElement.querySelector(qSel);
if (csrfField) {return csrfField;}

// Input element is placed outside the form
return Array.from(document.querySelectorAll(qSel))
.find((field) => field.form === formElement) || null;
}

/* stimulusFetch: 'lazy' */
export default 'csrf-protection-controller';
Loading