common.js 2.4 KB

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