Skip to content

Commit d499855

Browse files
committed
Merged in [7398] from rcross@amsl.com:
add X-CSRFToken AJAX request header. - Legacy-Id: 7407 Note: SVN reference [7398] has been migrated to Git commit 79a77b4
1 parent e1efe56 commit d499855

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

static/secretariat/js/utils.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,54 @@
11
/* utils.js - utility functions */
22

3+
// set X-CSRFToken AJAX request header
4+
// from https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
5+
6+
function getCookie(name) {
7+
var cookieValue = null;
8+
if (document.cookie && document.cookie != '') {
9+
var cookies = document.cookie.split(';');
10+
for (var i = 0; i < cookies.length; i++) {
11+
var cookie = jQuery.trim(cookies[i]);
12+
// Does this cookie string begin with the name we want?
13+
if (cookie.substring(0, name.length + 1) == (name + '=')) {
14+
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
15+
break;
16+
}
17+
}
18+
}
19+
return cookieValue;
20+
}
21+
var csrftoken = getCookie('csrftoken');
22+
23+
function csrfSafeMethod(method) {
24+
// these HTTP methods do not require CSRF protection
25+
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
26+
}
27+
function sameOrigin(url) {
28+
// test that a given url is a same-origin URL
29+
// url could be relative or scheme relative or absolute
30+
var host = document.location.host; // host + port
31+
var protocol = document.location.protocol;
32+
var sr_origin = '//' + host;
33+
var origin = protocol + sr_origin;
34+
// Allow absolute or scheme relative URLs to same origin
35+
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
36+
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
37+
// or any other URL that isn't scheme relative or absolute i.e relative.
38+
!(/^(\/\/|http:|https:).*/.test(url));
39+
}
40+
$.ajaxSetup({
41+
beforeSend: function(xhr, settings) {
42+
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
43+
// Send the token to same-origin, relative URLs only.
44+
// Send the token only if the method warrants CSRF protection
45+
// Using the CSRFToken value acquired earlier
46+
xhr.setRequestHeader("X-CSRFToken", csrftoken);
47+
}
48+
}
49+
});
50+
51+
// end set csrftoken
352

453
//returns the requested GET parameter from the URL
554
function get_param(param) {

0 commit comments

Comments
 (0)