2021-03-25 23:20:18 +01:00
|
|
|
import $ from "jquery";
|
2021-03-23 08:42:16 +01:00
|
|
|
|
2021-06-14 01:34:32 +02:00
|
|
|
export let csrf_token: string | undefined;
|
2020-08-01 03:43:15 +02:00
|
|
|
|
2020-07-02 01:45:54 +02:00
|
|
|
$(() => {
|
2018-12-17 00:15:52 +01:00
|
|
|
// This requires that we used Jinja2's {% csrf_input %} somewhere on the page.
|
2019-11-02 00:06:25 +01:00
|
|
|
const csrf_input = $('input[name="csrfmiddlewaretoken"]');
|
2021-03-25 23:20:18 +01:00
|
|
|
csrf_token = csrf_input.attr("value");
|
2018-12-17 00:23:34 +01:00
|
|
|
if (csrf_token === undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-12-17 00:15:52 +01:00
|
|
|
$.ajaxSetup({
|
2021-06-14 01:34:32 +02:00
|
|
|
beforeSend(xhr: JQuery.jqXHR, settings: JQuery.AjaxSettings) {
|
|
|
|
if (settings.url === undefined || csrf_token === undefined) {
|
|
|
|
throw new Error("settings.url and/or csrf_token are missing.");
|
|
|
|
}
|
|
|
|
|
2018-12-17 00:15:52 +01:00
|
|
|
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
|
|
|
|
// Only send the token to relative URLs i.e. locally.
|
|
|
|
xhr.setRequestHeader("X-CSRFToken", csrf_token);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
});
|