Skip to content

Instantly share code, notes, and snippets.

@vmihailenco
Created August 3, 2011 19:24
Show Gist options
  • Save vmihailenco/1123548 to your computer and use it in GitHub Desktop.
Save vmihailenco/1123548 to your computer and use it in GitHub Desktop.
$(document).ajaxSend (event, xhr, settings) ->
getCookie = (name) ->
name += '='
if document.cookie and document.cookie != ''
cookies = document.cookie.split ';'
for cookie in cookies
cookie = jQuery.trim cookie
# Does this cookie string begin with the name we want?
if cookie.substring(0, name.length) == name
return decodeURIComponent cookie.substring(name.length)
return null
sameOrigin = (url) ->
# url could be relative or scheme relative or absolute
host = document.location.host # host + port
protocol = document.location.protocol
sr_origin = '//' + host
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))
safeMethod = (method) ->
return /^(GET|HEAD|OPTIONS|TRACE)$/.test method
if not safeMethod(settings.type) and sameOrigin(settings.url)
xhr.setRequestHeader "X-CSRFToken", getCookie('csrftoken')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment