~widelands-dev/widelands-website/trunk

« back to all changes in this revision

Viewing changes to media/js/jquery_csrf_ajax.js

  • Committer: Holger Rapp
  • Date: 2009-02-26 22:38:49 UTC
  • Revision ID: sirver@kallisto.local-20090226223849-1563ij0uuw0lz0zu
First version of widelands online help

Show diffs side-by-side

added added

removed removed

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