Poller cleanup and corrections. CSRF protection for js included
authorLeonidas Poulopoulos <leopoul@noc.grnet.gr>
Fri, 9 Dec 2011 15:59:56 +0000 (17:59 +0200)
committerLeonidas Poulopoulos <leopoul@noc.grnet.gr>
Fri, 9 Dec 2011 15:59:56 +0000 (17:59 +0200)
poller/views.py
static/js/jquery_csrf_protect.js [new file with mode: 0644]
templates/base.html
templates/poller.js
utils/proxy.py

index 469f2b8..3088fc0 100644 (file)
@@ -11,7 +11,7 @@ from django.template.loader import render_to_string
 from django.http import HttpResponse
 from gevent.event import Event
 from django.conf import settings
-from django.views.decorators.csrf import csrf_exempt
+#from django.views.decorators.csrf import csrf_exempt
 from django.http import HttpResponseRedirect
 from django.core.urlresolvers import reverse
 
@@ -37,7 +37,7 @@ def json_response(value, **kwargs):
     return HttpResponse(simplejson.dumps(value), **kwargs)
 
 class Msgs(object):
-    cache_size = 200
+    cache_size = 500
 
     def __init__(self):
         self.user = None
@@ -52,7 +52,6 @@ class Msgs(object):
             request.session['cursor'] = self.user_cache[-1]['id']
         return render_to_response('poll.html', {'messages': self.user_cache})
 
-    @csrf_exempt
     def message_existing(self, request):
         if request.is_ajax():
             try:
@@ -72,9 +71,8 @@ class Msgs(object):
                 self.user_cache[user] = []
                 self.user_cursor[user] = ''
             return json_response({'messages': self.user_cache[user]})
-        return HttpResponseRedirect(reverse('login'))
+        return HttpResponseRedirect(reverse('group-routes'))
     
-    @csrf_exempt
     def message_new(self, mesg=None):
         if mesg:
             message = mesg['message']
@@ -97,7 +95,6 @@ class Msgs(object):
         self.new_message_user_event[user].clear()
         return json_response(msg)
     
-    @csrf_exempt
     def message_updates(self, request):
         if request.is_ajax():
             cursor = {}
@@ -126,7 +123,7 @@ class Msgs(object):
             finally:
                 if self.user_cache[user]:
                     self.user_cursor[user] = self.user_cache[user][-1]['id']
-        return HttpResponseRedirect(reverse('login'))
+        return HttpResponseRedirect(reverse('group-routes'))
     #            else:
     #                request.session.pop('cursor', None)
 
diff --git a/static/js/jquery_csrf_protect.js b/static/js/jquery_csrf_protect.js
new file mode 100644 (file)
index 0000000..349191b
--- /dev/null
@@ -0,0 +1,36 @@
+$(document).ajaxSend(function(event, xhr, settings) {
+    function getCookie(name) {
+        var cookieValue = null;
+        if (document.cookie && document.cookie != '') {
+            var cookies = document.cookie.split(';');
+            for (var i = 0; i < cookies.length; i++) {
+                var cookie = jQuery.trim(cookies[i]);
+                // Does this cookie string begin with the name we want?
+                if (cookie.substring(0, name.length + 1) == (name + '=')) {
+                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
+                    break;
+                }
+            }
+        }
+        return cookieValue;
+    }
+    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", getCookie('csrftoken'));
+    }
+});
\ No newline at end of file
index 2853be8..4c66a87 100644 (file)
@@ -6,6 +6,7 @@
 <META HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">
 
 <script src="/static/js/jquery.min.js" type="text/javascript"></script>
+<script src="/static/js/jquery_csrf_protect.js" type="text/javascript"></script>
 <link rel="stylesheet" type="text/css" href="/static/css/base.css">
 <link rel="stylesheet" type="text/css" href="/static/css/smoothness/jquery-ui-1.8.13.custom.css">
 <script type="text/javascript" src="/static/js/jquery-ui-1.8.12.custom.min.js"></script>
index 2effc47..970e28e 100644 (file)
@@ -27,8 +27,10 @@ $(document).ready(function() {
        }
     });
     $("#message").select();
+    {% if user.is_authenticated %}
     updater.start();
     updater.poll();
+    {% endif %}
 });
 
 function newMessage(form) {
@@ -52,8 +54,7 @@ function getCookie(name) {
 }
 
 jQuery.postJSON = function(url, args, callback) {
-    args._xsrf = getCookie("_xsrf");
-    $.ajax({url: url, data: $.param(args), dataType: "text", type: "POST",
+    $.ajax({url: url, dataType: "text", type: "POST",
            success: function(response) {
        if (callback) callback(eval("(" + response + ")"));
     }, error: function(response) {
@@ -90,19 +91,17 @@ var updater = {
     cursor: null,
     
     start: function() {
-       var args = {"_xsrf": getCookie("_xsrf")};
-       if (updater.cursor) args.cursor = updater.cursor;
        $.ajax({url: "{% url fetch-existing %}", type: "POST", dataType: "text",
-               data: $.param(args), success: updater.onFetchExisting,
+               success: updater.onFetchExisting,
                error: updater.onError});
         },
     
     poll: function() {
-       var args = {"_xsrf": getCookie("_xsrf")};
-       if (updater.cursor) args.cursor = updater.cursor;
+       {% if user.is_authenticated %}
        $.ajax({url: "{% url fetch-updates %}", type: "POST", dataType: "text",
-               data: $.param(args), success: updater.onSuccess,
+               success: updater.onSuccess,
                error: updater.onError});
+       {% endif %}
     },
 
     onSuccess: function(response) {
index 0ca4f70..c894504 100644 (file)
@@ -43,7 +43,7 @@ class Retriever(object):
         else:
             device = self.proccess_xml()
             if device.routing_options:
-                cache.set("device", device, 600)
+                cache.set("device", device)
                 return device
             else:
                 return False
@@ -188,7 +188,7 @@ class Applier(object):
                                     logger.info("Successfully committed @ %s" % self.device)
                                     newconfig = m.get_config(source='running', filter=('subtree',settings.ROUTES_FILTER)).data_xml
                                     retrieve = Retriever(xml=newconfig)
-                                    cache.set("device", retrieve.proccess_xml(), 600)
+                                    cache.set("device", retrieve.proccess_xml())
                                     
                                     if not commit_is_successful:
                                         raise Exception()