csrf.js 1.7 KB

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