Skip to content

Commit

Permalink
Add a custom X-CSRFToken header to each XMLHttpRequest to be Django 1…
Browse files Browse the repository at this point in the history
….3 compatible

Closes #4
  • Loading branch information
tobami committed Oct 21, 2011
1 parent a7ce2c3 commit 865e9be
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion overmind/api/test_provisioning.py
Expand Up @@ -49,7 +49,7 @@ def setUp(self):
self.p3.save()

def test_not_authenticated(self):
'''A non authenticated user should get 401'''
"""Should get a 401 when the user is not authenticated"""
# NOTE: Use non-authenticated client
response = self.client.get(self.path)
self.assertEquals(response.status_code, 401)
Expand Down
38 changes: 38 additions & 0 deletions overmind/media/js/main.js
@@ -1,3 +1,41 @@
$(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'));
}
});


function confirmation(message, target) {
var answer = confirm(message);
if (answer){
Expand Down

0 comments on commit 865e9be

Please sign in to comment.