42 lines
1.8 KiB
HTML
42 lines
1.8 KiB
HTML
{{define "csrf_script"}}
|
|
<script>
|
|
// Auto-applies CSRF protection to every plain <form method=post> and every
|
|
// same-origin mutating fetch() call on this page — no per-form or per-fetch-call
|
|
// changes needed anywhere else in this codebase. See internal/webui/csrf.go for
|
|
// the server-side check this token has to satisfy.
|
|
window.__csrfToken = {{.csrf_token}};
|
|
(function() {
|
|
var token = window.__csrfToken;
|
|
if (!token) return; // no session cookie yet (e.g. the login page itself)
|
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
document.querySelectorAll('form').forEach(function(form) {
|
|
if ((form.getAttribute('method') || '').toLowerCase() !== 'post') return;
|
|
if (form.querySelector('input[name="csrf_token"]')) return;
|
|
var input = document.createElement('input');
|
|
input.type = 'hidden';
|
|
input.name = 'csrf_token';
|
|
input.value = token;
|
|
form.appendChild(input);
|
|
});
|
|
});
|
|
|
|
var mutating = { POST: true, PUT: true, PATCH: true, DELETE: true };
|
|
var originalFetch = window.fetch.bind(window);
|
|
window.fetch = function(url, options) {
|
|
options = options || {};
|
|
var method = (options.method || 'GET').toUpperCase();
|
|
var isAbsolute = /^https?:\/\//i.test(url);
|
|
var isSameOrigin = !isAbsolute || url.indexOf(window.location.origin) === 0;
|
|
if (mutating[method] && isSameOrigin) {
|
|
options = Object.assign({}, options);
|
|
var headers = new Headers(options.headers || {});
|
|
headers.set('X-CSRF-Token', token);
|
|
options.headers = headers;
|
|
}
|
|
return originalFetch(url, options);
|
|
};
|
|
})();
|
|
</script>
|
|
{{end}}
|