You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/theme/venix/js/admin-csrf.js

87 lines
2.9 KiB
JavaScript

(function () {
"use strict";
var token = typeof window.ADMIN_CSRF_TOKEN === "string" ? window.ADMIN_CSRF_TOKEN : "";
if (!/^[a-f0-9]{64}$/.test(token)) return;
var unsafeMethods = { POST: true, PUT: true, PATCH: true, DELETE: true };
function requestDetails(url, method) {
var parsed;
try {
parsed = new URL(url || window.location.href, window.location.href);
} catch (error) {
return { protect: false, method: "GET" };
}
method = String(method || "GET").toUpperCase();
return {
protect:
parsed.origin === window.location.origin &&
(parsed.pathname === "/admin" || parsed.pathname.indexOf("/admin/") === 0) &&
unsafeMethods[method] === true,
method: method,
};
}
if (typeof window.fetch === "function" && !window.fetch.__adminCsrfProtected) {
var nativeFetch = window.fetch;
var protectedFetch = function (input, init) {
var options = Object.assign({}, init || {});
var inputUrl = typeof input === "string" || input instanceof URL ? String(input) : input.url;
var inputMethod = input && typeof input === "object" && input.method ? input.method : "GET";
var details = requestDetails(inputUrl, options.method || inputMethod);
if (details.protect) {
var sourceHeaders = options.headers;
if (!sourceHeaders && input && typeof input === "object" && input.headers) {
sourceHeaders = input.headers;
}
var headers = new Headers(sourceHeaders || {});
headers.set("X-Admin-CSRF-Token", token);
options.headers = headers;
}
return nativeFetch.call(this, input, options);
};
protectedFetch.__adminCsrfProtected = true;
window.fetch = protectedFetch;
}
if (window.XMLHttpRequest && !window.XMLHttpRequest.prototype.__adminCsrfProtected) {
var nativeOpen = window.XMLHttpRequest.prototype.open;
var nativeSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.open = function (method, url) {
this.__adminCsrfRequired = requestDetails(url, method).protect;
return nativeOpen.apply(this, arguments);
};
window.XMLHttpRequest.prototype.send = function () {
if (this.__adminCsrfRequired) {
this.setRequestHeader("X-Admin-CSRF-Token", token);
}
return nativeSend.apply(this, arguments);
};
window.XMLHttpRequest.prototype.__adminCsrfProtected = true;
}
document.addEventListener(
"submit",
function (event) {
var form = event.target;
if (!form || String(form.tagName).toLowerCase() !== "form") return;
if (!requestDetails(form.action || window.location.href, form.method || "GET").protect) return;
var field = form.querySelector('input[name="_admin_csrf"]');
if (!field) {
field = document.createElement("input");
field.type = "hidden";
field.name = "_admin_csrf";
form.appendChild(field);
}
field.value = token;
},
true
);
})();