This repository has been archived on 2023-03-18. You can view files and clone it, but cannot push or open issues or pull requests.
osr-discourse-src/app/assets/javascripts/discourse/initializers/csrf-token.js.es6
Robin Ward 3d7c26c15e FIX: Memory Leaks w/ Container (#7750)
Gives instance initializers the ability to add a `teardown` method that
will be called between tests to clean up after themselves.
2019-06-11 18:41:27 +02:00

29 lines
677 B
JavaScript

// Append our CSRF token to AJAX requests when necessary.
let installed = false;
let callbacks = $.Callbacks();
export default {
name: "csrf-token",
initialize(container) {
// Add a CSRF token to all AJAX requests
let session = container.lookup("session:main");
session.set("csrfToken", $("meta[name=csrf-token]").attr("content"));
if (!installed) {
$.ajaxPrefilter(callbacks.fire);
installed = true;
}
callbacks.add(function(options, originalOptions, xhr) {
if (!options.crossDomain) {
xhr.setRequestHeader("X-CSRF-Token", session.get("csrfToken"));
}
});
},
teardown() {
callbacks.empty();
}
};