-
Notifications
You must be signed in to change notification settings - Fork 1
/
etools-ajax-utils.js
184 lines (166 loc) · 4.6 KB
/
etools-ajax-utils.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
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/* eslint-disable linebreak-style */
import './scripts/es6-obj-assign-polyfil.js';
export function getCsrfHeader(csrfCheck, method) {
if (!!method && csrfSafeMethod(method)) {
return {};
}
const csrfHeaders = {};
if (csrfCheck !== 'disabled') {
const csrfToken = _getCSRFCookie();
if (csrfToken) {
csrfHeaders['x-csrftoken'] = csrfToken;
}
}
return csrfHeaders;
}
export function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);
}
export function _getCSRFCookie() {
// check for a csrftoken cookie and return its value
const csrfCookieName = 'csrftoken';
let csrfToken = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, csrfCookieName.length + 1) === csrfCookieName + '=') {
csrfToken = decodeURIComponent(cookie.substring(csrfCookieName.length + 1));
break;
}
}
}
return csrfToken;
}
export function tryJsonParse(response) {
try {
return JSON.parse(response);
} catch (e) {
return response;
}
}
export function getClientConfiguredHeaders(additionalHeaders) {
let header;
const clientHeaders = {};
if (additionalHeaders && additionalHeaders instanceof Object) {
/* eslint-disable guard-for-in */
for (header in additionalHeaders) {
clientHeaders[header] = additionalHeaders[header].toString();
}
/* eslint-enable guard-for-in */
}
return clientHeaders;
}
export async function getRequestHeaders(reqConfig) {
let headers = {};
headers['content-type'] = determineContentType(reqConfig.body);
const authHeader = await getAuthorizationHeader(reqConfig.endpoint);
if (window.EtoolsLanguage) {
headers['language'] = window.EtoolsLanguage;
}
headers = Object.assign(
{},
headers,
getClientConfiguredHeaders(reqConfig.headers),
authHeader,
getCsrfHeader(reqConfig.csrfCheck, reqConfig.method)
);
return headers;
}
async function getAuthorizationHeader(endpoint) {
if (endpoint.token_key) {
let token = localStorage.getItem(endpoint.token_key);
if (window.AppMsalInstance) {
try {
token = await window.AppMsalInstance.acquireTokenSilent();
} catch (err) {
window.location.reload(true);
}
}
return {
Authorization: 'JWT ' + token
};
}
return {};
}
/**
* Content-Type set here can be overridden later
* by headers sent from the client
*/
export function determineContentType(body) {
let contentType = 'application/json';
if (typeof body === 'string') {
contentType = 'application/x-www-form-urlencoded';
}
return contentType;
}
export function isNonEmptyObject(obj) {
return obj && typeof obj === 'object' && Object.keys(obj).length > 0;
}
/**
*
* @param {
* {
* endpoint: {
* url: string,
* exp?: number,
* cacheTableName?: string,
* cachingKey?: string
* },
* body: any,
* method: string,
* headers: any,
* csrfCheck: string // 'disabled',
* timeout: number,
* sync: boolean,
* handleAs: string,
* jsonPrefix: string,
* rejectWithRequest: boolean,
* withCredentials: boolean,
* }
* } reqConfig
*/
export async function getIronRequestConfigOptions(etoolAjaxReqConfig) {
etoolAjaxReqConfig.method = etoolAjaxReqConfig.method || 'GET';
const headers = await getRequestHeaders(etoolAjaxReqConfig);
return {
url: getRequestUrl(etoolAjaxReqConfig),
method: etoolAjaxReqConfig.method,
headers,
body: etoolAjaxReqConfig.body || {},
async: !etoolAjaxReqConfig.sync,
handleAs: etoolAjaxReqConfig.handleAs || 'json',
jsonPrefix: etoolAjaxReqConfig.jsonPrefix || '',
withCredentials: !!etoolAjaxReqConfig.withCredentials,
timeout: etoolAjaxReqConfig.timeout || 0,
rejectWithRequest: true
};
}
export function getRequestUrl(reqConfig) {
let url = reqConfig.endpoint.url;
if (reqConfig.params) {
url += buildQueryString(url, reqConfig.params);
}
return url;
}
export function buildQueryString(url, params) {
let queryStr = '';
if (!params || !isNonEmptyObject(params)) {
return '';
}
if (url.indexOf('?') < 0) {
queryStr = '?';
} else {
queryStr = '&';
}
/* eslint-disable guard-for-in */
for (const key in params) {
queryStr += key + '=' + params[key] + '&';
}
/* eslint-enable guard-for-in */
// remove trailing &
queryStr = queryStr.substring(0, queryStr.length - 1);
return queryStr;
}