|
1 | 1 | /* utils.js - utility functions */ |
2 | 2 |
|
| 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 |
3 | 52 |
|
4 | 53 | //returns the requested GET parameter from the URL |
5 | 54 | function get_param(param) { |
|
0 commit comments