From 6142ea5547c3743a371331fe93129ac9f8e8438c Mon Sep 17 00:00:00 2001
From: Peter Rotich <peter@osticket.com>
Date: Fri, 20 Jul 2012 12:24:58 -0400
Subject: [PATCH] Add CSRF header to ajax calls - .ajaxSetup moved from
 original class.csrf.php (jared's class)

---
 scp/js/scp.js | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)

diff --git a/scp/js/scp.js b/scp/js/scp.js
index 81f554fb8..c46c624d4 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',
-- 
GitLab