Project

General

Profile

Download (7.03 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * @file
3
 *
4
 * Rewrites XMLHttpRequest to automatically send CSRF token with it. In theory
5
 * plays nice with other JavaScript libraries, needs testing though.
6
 */
7

    
8
// Here are the basic overloaded method definitions
9
// The wrapper must be set BEFORE onreadystatechange is written to, since
10
// a bug in ActiveXObject prevents us from properly testing for it.
11
CsrfMagic = function(real) {
12
    // try to make it ourselves, if you didn't pass it
13
    if (!real) try { real = new XMLHttpRequest; } catch (e) {;}
14
    if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {;}
15
    if (!real) try { real = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {;}
16
    if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP.4.0'); } catch (e) {;}
17
    this.csrf = real;
18
    // properties
19
    var csrfMagic = this;
20
    real.onreadystatechange = function() {
21
        csrfMagic._updateProps();
22
        return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null;
23
    };
24
    csrfMagic._updateProps();
25
}
26

    
27
CsrfMagic.prototype = {
28

    
29
    open: function(method, url, async, username, password) {
30
        if (method == 'POST') this.csrf_isPost = true;
31
        // deal with Opera bug, thanks jQuery
32
        if (username) return this.csrf_open(method, url, async, username, password);
33
        else return this.csrf_open(method, url, async);
34
    },
35
    csrf_open: function(method, url, async, username, password) {
36
        if (username) return this.csrf.open(method, url, async, username, password);
37
        else return this.csrf.open(method, url, async);
38
    },
39

    
40
    send: function(data) {
41
        if (!this.csrf_isPost) return this.csrf_send(data);
42
        prepend = csrfMagicName + '=' + csrfMagicToken + '&';
43

    
44
 //		Removed to eliminate 'Refused to set unsafe header "Content-length" ' errors in modern browsers
45
 //       if (this.csrf_purportedLength === undefined) {
46
 //           this.csrf_setRequestHeader("Content-length", this.csrf_purportedLength + prepend.length);
47
 //           delete this.csrf_purportedLength;
48
 //       }
49

    
50
        delete this.csrf_isPost;
51
        return this.csrf_send(prepend + data);
52
    },
53
    csrf_send: function(data) {
54
        return this.csrf.send(data);
55
    },
56

    
57
    setRequestHeader: function(header, value) {
58
        // We have to auto-set this at the end, since we don't know how long the
59
        // nonce is when added to the data.
60
        if (this.csrf_isPost && header == "Content-length") {
61
            this.csrf_purportedLength = value;
62
            return;
63
        }
64
        return this.csrf_setRequestHeader(header, value);
65
    },
66
    csrf_setRequestHeader: function(header, value) {
67
        return this.csrf.setRequestHeader(header, value);
68
    },
69

    
70
    abort: function() {
71
        return this.csrf.abort();
72
    },
73
    getAllResponseHeaders: function() {
74
        return this.csrf.getAllResponseHeaders();
75
    },
76
    getResponseHeader: function(header) {
77
        return this.csrf.getResponseHeader(header);
78
    } // ,
79
}
80

    
81
// proprietary
82
CsrfMagic.prototype._updateProps = function() {
83
    this.readyState = this.csrf.readyState;
84
    if (this.readyState == 4) {
85
        this.responseText = this.csrf.responseText;
86
        this.responseXML  = this.csrf.responseXML;
87
        this.status       = this.csrf.status;
88
        this.statusText   = this.csrf.statusText;
89
    }
90
}
91
CsrfMagic.process = function(base) {
92
    var prepend = csrfMagicName + '=' + csrfMagicToken;
93
    if (base) return prepend + '&' + base;
94
    return prepend;
95
}
96
// callback function for when everything on the page has loaded
97
CsrfMagic.end = function() {
98
    // This rewrites forms AGAIN, so in case buffering didn't work this
99
    // certainly will.
100
    forms = document.getElementsByTagName('form');
101
    for (var i = 0; i < forms.length; i++) {
102
        form = forms[i];
103
        if (form.method.toUpperCase() !== 'POST') continue;
104
        if (form.elements[csrfMagicName]) continue;
105
        var input = document.createElement('input');
106
        input.setAttribute('name',  csrfMagicName);
107
        input.setAttribute('value', csrfMagicToken);
108
        input.setAttribute('type',  'hidden');
109
        form.appendChild(input);
110
    }
111
}
112

    
113
// Sets things up for Mozilla/Opera/nice browsers
114
// We very specifically match against Internet Explorer, since they haven't
115
// implemented prototypes correctly yet.
116
if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') {
117
    var x = XMLHttpRequest.prototype;
118
    var c = CsrfMagic.prototype;
119

    
120
    // Save the original functions
121
    x.csrf_open = x.open;
122
    x.csrf_send = x.send;
123
    x.csrf_setRequestHeader = x.setRequestHeader;
124

    
125
    // Notice that CsrfMagic is itself an instantiatable object, but only
126
    // open, send and setRequestHeader are necessary as decorators.
127
    x.open = c.open;
128
    x.send = c.send;
129
    x.setRequestHeader = c.setRequestHeader;
130
} else {
131
    // The only way we can do this is by modifying a library you have been
132
    // using. We support YUI, script.aculo.us, prototype, MooTools,
133
    // jQuery, Ext and Dojo.
134
    if (window.jQuery) {
135
        // jQuery didn't implement a new XMLHttpRequest function, so we have
136
        // to do this the hard way.
137
        jQuery.csrf_ajax = jQuery.ajax;
138
        jQuery.ajax = function( s ) {
139
            if (s.type && s.type.toUpperCase() == 'POST') {
140
                s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
141
                if ( s.data && s.processData && typeof s.data != "string" ) {
142
                    s.data = jQuery.param(s.data);
143
                }
144
                s.data = CsrfMagic.process(s.data);
145
            }
146
            return jQuery.csrf_ajax( s );
147
        }
148
    }
149
    if (window.Prototype) {
150
        // This works for script.aculo.us too
151
        Ajax.csrf_getTransport = Ajax.getTransport;
152
        Ajax.getTransport = function() {
153
            return new CsrfMagic(Ajax.csrf_getTransport());
154
        }
155
    }
156
    if (window.MooTools) {
157
        Browser.csrf_Request = Browser.Request;
158
        Browser.Request = function () {
159
            return new CsrfMagic(Browser.csrf_Request());
160
        }
161
    }
162
    if (window.YAHOO) {
163
        // old YUI API
164
        YAHOO.util.Connect.csrf_createXhrObject = YAHOO.util.Connect.createXhrObject;
165
        YAHOO.util.Connect.createXhrObject = function (transaction) {
166
            obj = YAHOO.util.Connect.csrf_createXhrObject(transaction);
167
            obj.conn = new CsrfMagic(obj.conn);
168
            return obj;
169
        }
170
    }
171
    if (window.Ext) {
172
        // Ext can use other js libraries as loaders, so it has to come last
173
        // Ext's implementation is pretty identical to Yahoo's, but we duplicate
174
        // it for comprehensiveness's sake.
175
        Ext.lib.Ajax.csrf_createXhrObject = Ext.lib.Ajax.createXhrObject;
176
        Ext.lib.Ajax.createXhrObject = function (transaction) {
177
            obj = Ext.lib.Ajax.csrf_createXhrObject(transaction);
178
            obj.conn = new CsrfMagic(obj.conn);
179
            return obj;
180
        }
181
    }
182
    if (window.dojo) {
183
        // NOTE: this doesn't work with latest dojo
184
        dojo.csrf__xhrObj = dojo._xhrObj;
185
        dojo._xhrObj = function () {
186
            return new CsrfMagic(dojo.csrf__xhrObj());
187
        }
188
    }
189
}
(1-1/2)