import pharos dashboard code
[pharos.git] / tools / pharos-dashboard / dashboard / static / js / csrf.js
1 /**
2  * use django csrf token in ajax requests
3  * source: https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax
4  */
5 // using jQuery
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
28 $.ajaxSetup({
29     beforeSend: function (xhr, settings) {
30         if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
31             xhr.setRequestHeader("X-CSRFToken", csrftoken);
32         }
33     }
34 });