-
Notifications
You must be signed in to change notification settings - Fork 24
/
csrf.js
52 lines (43 loc) · 1.35 KB
/
csrf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var CSRF = {
token: function () {
var token = document.querySelector('meta[name="csrf-token"]');
return token && token.getAttribute('content');
},
param: function () {
var param = document.querySelector('meta[name="csrf-param"]');
return param && param.getAttribute('content');
}
};
var sameOrigin = function (url) {
var a = document.createElement('a'), origin;
a.href = url;
origin = a.href.split('/', 3).join('/');
return window.location.href.indexOf(origin) === 0;
};
window.CSRF = CSRF;
document.addEventListener('ajax:before', function (e) {
var token = CSRF.token(), xhr = e.detail;
if (token)
xhr.setRequestHeader('X-CSRF-Token', token);
});
document.addEventListener('submit', function (e) {
var token = CSRF.token(),
param = CSRF.param(),
form = e.target;
if (matches.call(form, 'form')) {
if (matches.call(form, 'form[data-remote]'))
return true;
if (!form.method || form.method.toUpperCase() == 'GET')
return true;
if (!sameOrigin(form.action))
return true;
if (param && token && !form.querySelector('input[name='+param+']')) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', param);
input.setAttribute('value', token);
form.appendChild(input);
}
return true;
}
});