~chipaca/unity-lens-video/custom-user-agent

« back to all changes in this revision

Viewing changes to media/js/django-jquery-csrf.js

  • Committer: Janos Gyerik
  • Date: 2012-05-21 18:31:58 UTC
  • Revision ID: janos@axiom-20120521183158-kvtqzuo6yhe3mdzq
added example configuration for logging to file

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
////////////////////////////////////////////////////////////////
 
2
// jQuery.ajaxSend patch to send X-CSRFToken on all AJAX POST //
 
3
////////////////////////////////////////////////////////////////
 
4
$(document).ajaxSend(function(event, xhr, settings) {
 
5
    function getCookie(name) {
 
6
        var cookieValue = null;
 
7
        if (document.cookie && document.cookie != '') {
 
8
            var cookies = document.cookie.split(';');
 
9
            for (var i = 0; i < cookies.length; i++) {
 
10
                var cookie = jQuery.trim(cookies[i]);
 
11
                // Does this cookie string begin with the name we want?
 
12
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
 
13
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
 
14
                    break;
 
15
                }
 
16
            }
 
17
        }
 
18
        return cookieValue;
 
19
    }
 
20
    function sameOrigin(url) {
 
21
        // url could be relative or scheme relative or absolute
 
22
        var host = document.location.host; // host + port
 
23
        var protocol = document.location.protocol;
 
24
        var sr_origin = '//' + host;
 
25
        var origin = protocol + sr_origin;
 
26
        // Allow absolute or scheme relative URLs to same origin
 
27
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
 
28
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
 
29
            // or any other URL that isn't scheme relative or absolute i.e relative.
 
30
            !(/^(\/\/|http:|https:).*/.test(url));
 
31
    }
 
32
    function safeMethod(method) {
 
33
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
 
34
    }
 
35
 
 
36
    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
 
37
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
 
38
    }
 
39
});
 
40
 
 
41
// eof