This repository has been archived by the owner on Feb 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathxsrfUtils.js
66 lines (58 loc) · 1.74 KB
/
xsrfUtils.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
/*******************************************************************************
* Copyright (c) 2014 SAP AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SAP AG - initial API and implementation
*******************************************************************************/
define(['module'],function(module){
var XSRF_TOKEN = "x-csrf-token";//$NON-NLS-0$
/**
* extracts value of xsrf cookie if available
*/
function getCSRFToken() {
if (typeof document === "undefined") return null;
var config = module.config && module.config() || {};
if (config.CSRF_TOKEN) {
return config.CSRF_TOKEN;
}
var cookies = document.cookie.split(";");//$NON-NLS-0$
var i,n,v;
for(i = 0; i<cookies.length; i++) {
n = cookies[i].substr(0, cookies[i].indexOf("=")).trim();//$NON-NLS-0$
v = cookies[i].substr(cookies[i].indexOf("=") + 1).trim();//$NON-NLS-0$
if(n.endsWith(XSRF_TOKEN)) {
return v;
}
}
}
/**
* adds xsrf nonce to header if set in cookies
* @param {Object} request header
*/
function setNonceHeader(headers) {
var token = getCSRFToken();
if (token) {
headers[XSRF_TOKEN] = token;
}
}
/**
* adds xsrf nonce to an XMLHTTPRequest object if set in cookies
* @param {Object} XMLHttpRequest object
*/
function addCSRFNonce(request) {
var token = getCSRFToken();
if(token) {
request.setRequestHeader(XSRF_TOKEN, token);
}
}
return {
XSRF_TOKEN: XSRF_TOKEN,
getCSRFToken: getCSRFToken,
setNonceHeader: setNonceHeader,
addCSRFNonce: addCSRFNonce
};
});