diff --git a/scp/js/scp.js b/scp/js/scp.js index 81f554fb8db407668e0d36ba1a101d36e8f9fbdd..c46c624d49ca97127b9bca3485c6dd313c53497b 100644 --- a/scp/js/scp.js +++ b/scp/js/scp.js @@ -173,7 +173,34 @@ $(document).ready(function(){ - /* global inits */ + /************ global inits *****************/ + + //Add CSRF token to the ajax requests. + // Many thanks to https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ + jared. + $(document).ajaxSend(function(event, xhr, settings) { + + function sameOrigin(url) { + // url could be relative or scheme relative or absolute + var host = document.location.host; // host + port + var protocol = document.location.protocol; + var sr_origin = '//' + host; + var origin = protocol + sr_origin; + // Allow absolute or scheme relative URLs to same origin + return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || + (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || + // or any other URL that isn't scheme relative or absolute i.e + // relative. + !(/^(\/\/|http:|https:).*/.test(url)); + } + + function safeMethod(method) { + return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); + } + if (!safeMethod(settings.type) && sameOrigin(settings.url)) { + xhr.setRequestHeader("X-CSRFToken", $("meta[name=csrf_token]").attr("content")); + } + + }); /* Get config settings from the backend */ $.get('ajax.php/config/ui.json',