-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
nonce.js
50 lines (44 loc) · 1.14 KB
/
nonce.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
/**
* External dependencies
*/
import { addAction } from '@wordpress/hooks';
const createNonceMiddleware = ( nonce ) => {
let usedNonce = nonce;
/**
* This is not ideal but it's fine for now.
*
* Configure heartbeat to refresh the wp-api nonce, keeping the editor
* authorization intact.
*/
addAction( 'heartbeat.tick', 'core/api-fetch/create-nonce-middleware', ( response ) => {
if ( response[ 'rest-nonce' ] ) {
usedNonce = response[ 'rest-nonce' ];
}
} );
return function( options, next ) {
let headers = options.headers || {};
// If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
let addNonceHeader = true;
for ( const headerName in headers ) {
if ( headers.hasOwnProperty( headerName ) ) {
if ( headerName.toLowerCase() === 'x-wp-nonce' ) {
addNonceHeader = false;
break;
}
}
}
if ( addNonceHeader ) {
// Do not mutate the original headers object, if any.
headers = {
...headers,
'X-WP-Nonce': usedNonce,
};
}
return next( {
...options,
headers,
} );
};
};
export default createNonceMiddleware;