Skip to content

Commit

Permalink
include Rails CSRF protection tokens in m.request data
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Powell committed Oct 6, 2015
1 parent 234769e commit 0a1c690
Showing 1 changed file with 38 additions and 3 deletions.
41 changes: 38 additions & 3 deletions app/assets/javascripts/mithril_ujs.js
Expand Up @@ -31,11 +31,46 @@
}
};

// Rails CSRF protection

var CSRFparam = '', CSRFtoken = '';

var setUpCSRF = function() {
if ($) {
CSRFparam = $("[name=csrf-param]").attr("content");
CSRFtoken = $("[name=csrf-token]").attr("content");
} else {
var el;

if (el = document.querySelector("[name=csrf-param]"))
CSRFparam = el.getAttribute("content");
if (el = document.querySelector("[name=csrf-token]"))
CSRFtoken = el.getAttribute("content");
}

if (CSRFparam && CSRFtoken && !m.requestWithoutCSRFProtection) {
m.requestWithoutCSRFProtection = m.request;
m.request = function(options) {
var data = options.data || {};
if (options.method && !/^(GET|HEAD)$/i.test(options.method)) {
data[CSRFparam] = CSRFtoken;
options.data = data;
}
m.requestWithoutCSRFProtection(options);
};
}
};

var initMithrilUJS = function() {
setUpCSRF();
mountComponents();
};

// Register page load & unload events
if ($) {
$(mountComponents);
$(initMithrilUJS);
} else {
document.addEventListener('DOMContentLoaded', mountComponents);
document.addEventListener('DOMContentLoaded', initMithrilUJS);
}

// Turbolinks specified events
Expand All @@ -50,6 +85,6 @@
document.addEventListener(eventName, callback);
}
}
handleEvent('page:change', mountComponents);
handleEvent('page:change', initMithrilUJS);
}
})(document, window, m);

0 comments on commit 0a1c690

Please sign in to comment.