-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
155 lines (126 loc) · 5.25 KB
/
index.js
File metadata and controls
155 lines (126 loc) · 5.25 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import jQuery from 'jquery';
let $ = jQuery;
const config = {};
let token = null;
// Function ripped from Django docs.
// See: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
function csrfSafeMethod(method) {
// These HTTP methods do not require CSRF protection.
return (/^(GET|HEAD|OPTIONS|TRACE)$/i.test(method));
}
function csrfPrefilter(options, ...args) {
// The header should only be set when the request is local.
if (!csrfSafeMethod(options.type) && !options.crossDomain) {
const oldBeforeSend = options.beforeSend;
options.beforeSend = function (xhr) {
// The csrf token is valid for the duration of the session,
// so it's safe to use a static token.
xhr.setRequestHeader(config.key, token);
if (oldBeforeSend) {
oldBeforeSend(...args);
}
};
}
}
export function setToken(newToken) {
token = newToken;
}
/* Patch $.ajax to support expired CSRF tokens */
function addRetrySupport(retryURL, parseResponse, isCSRFFailure) {
if (!isCSRFFailure) {
isCSRFFailure = xhr => xhr.status === 403;
}
const originalAjax = $.ajax;
/**
* Copy properties from jqXhrToCopy to fakeJqXhr. This is makes fakeJqXhr
* behave properly.
*/
function fakeJqXhrInheritance(fakeJqXhr, jqXhrToCopy) {
Object.keys(jqXhrToCopy).forEach((key) => {
if (typeof jqXhrToCopy[key] === 'function') {
fakeJqXhr[key] = jqXhrToCopy[key].bind(jqXhrToCopy);
} else {
fakeJqXhr[key] = jqXhrToCopy[key];
}
});
}
/**
* Patch $.ajax to support expired csrf tokens. If a request is made and the
* token is expired, then a new token is fetched from the server. The original
* request will be run again with the new token.
*
* For the outside world only 1 request is send, but depending on the situation
* at most 3 request can be executed.
*/
$.ajax = function (url, options) {
const pResult = $.Deferred(); // eslint-disable-line new-cap
const fakeJqXhr = pResult.promise();
if (typeof url === 'object') {
options = url;
url = undefined;
} else {
options.url = url;
}
// The original ajax request might have success or error callbacks. We want
// to trigger them manually based on if there is a csrf token mismatch.
const success = options.success;
const error = options.error;
delete options.success;
delete options.error;
// Fire the first try!
const xhrFirstTry = originalAjax(options);
xhrFirstTry.error((jqXHR, textStatus, errorThrown) => {
if (isCSRFFailure(jqXHR)) {
// We assume that a csrf token mismatch happend, so fetch a new
// token and retry with the correct token.
originalAjax(retryURL).done((data) => {
setToken(parseResponse(data));
let xhrSecondTry = null;
options.success = (dataSecondSuccess, textStatusSecondSuccess, jqXHRSecondSuccess) => {
if (typeof success === 'function') success(dataSecondSuccess, textStatusSecondSuccess, jqXHRSecondSuccess);
pResult.resolve(dataSecondSuccess, textStatusSecondSuccess, jqXHRSecondSuccess);
};
options.error = (jqXHRSecondError, textStatusSecondError, errorThrownSecondError) => {
if (typeof error === 'function') error(jqXHRSecondError, textStatusSecondError, errorThrownSecondError);
pResult.reject(jqXHRSecondError, textStatusSecondError, errorThrownSecondError);
};
xhrSecondTry = originalAjax(options);
fakeJqXhrInheritance(fakeJqXhr, xhrSecondTry);
});
} else {
// Some other error happend, so just pass it through.
fakeJqXhrInheritance(fakeJqXhr, xhrFirstTry);
if (typeof error === 'function') error(jqXHR, textStatus, errorThrown);
pResult.reject(jqXHR, textStatus, errorThrown);
}
});
// Upon success, update our fakeJqXhr and trigger the success callback.
xhrFirstTry.success((data, textStatus, jqXHR) => {
fakeJqXhrInheritance(fakeJqXhr, xhrFirstTry);
if (typeof success === 'function') success(data, textStatus, jqXHR);
pResult.resolve(data, textStatus, jqXHR);
});
fakeJqXhrInheritance(fakeJqXhr, xhrFirstTry);
return fakeJqXhr;
};
}
export function enable(newToken, newConfig) {
newConfig || (newConfig = {});
if (!newToken) {
console.warn('CSRF token is not set!');
}
if (!newConfig.key) {
newConfig.key = 'X-CSRF-TOKEN';
}
config.key = newConfig.key;
if (newConfig.retry) {
addRetrySupport(newConfig.retry.url, newConfig.retry.parseResponse,
newConfig.retry.isCSRFFailure);
}
setToken(newToken);
// Set a header on every request with the current csrf token in it.
$.ajaxPrefilter(csrfPrefilter);
}
export function mockJQuery(mockedJquery) {
$ = mockedJquery;
}