Files

64 lines
1.9 KiB
JavaScript

/* Skuld — patch window.fetch so every same-origin call carries the CSRF token.
*
* The server sends the CSRF secret in a script-readable cookie (skuld_csrf)
* next to the HttpOnly session cookie. This file copies it into the
* X-CSRF-Token header of every mutating call, and sends the browser to /login
* when the session has gone.
*
* Load this before app.js.
*/
(function () {
"use strict";
var MUTATING = ["POST", "PATCH", "PUT", "DELETE"];
var CSRF_COOKIE = "skuld_csrf";
function readCookie(name) {
var prefix = name + "=";
var parts = document.cookie ? document.cookie.split("; ") : [];
for (var i = 0; i < parts.length; i += 1) {
if (parts[i].indexOf(prefix) === 0) {
return decodeURIComponent(parts[i].slice(prefix.length));
}
}
return "";
}
function isSameOrigin(url) {
if (!url) {
return true;
}
if (url.indexOf("//") === -1) {
return true;
}
return url.indexOf(window.location.origin) === 0;
}
var nativeFetch = window.fetch ? window.fetch.bind(window) : null;
if (!nativeFetch) {
return;
}
window.fetch = function (input, init) {
var options = init ? Object.assign({}, init) : {};
var url = typeof input === "string" ? input : (input && input.url) || "";
var method = (options.method || (input && input.method) || "GET").toUpperCase();
if (isSameOrigin(url) && MUTATING.indexOf(method) !== -1) {
var headers = new Headers(options.headers || (input && input.headers) || {});
if (!headers.has("X-CSRF-Token")) {
headers.set("X-CSRF-Token", readCookie(CSRF_COOKIE));
}
options.headers = headers;
}
return nativeFetch(input, options).then(function (response) {
if (response.status === 401 && window.location.pathname !== "/login") {
window.location.href = "/login";
}
return response;
});
};
})();