Skip to content

Commit

Permalink
Nonce Middleware: Wrap the nonce middleware function into it's own fu…
Browse files Browse the repository at this point in the history
…nction that isn't regenerated on every API request. (#11347)

This allows the nonce to be updated during pageloads.
  • Loading branch information
dd32 authored and earnjam committed Nov 1, 2018
1 parent 9b4ef60 commit 6808261
Showing 1 changed file with 25 additions and 22 deletions.
47 changes: 25 additions & 22 deletions packages/api-fetch/src/middlewares/nonce.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
*/
import { addAction } from '@wordpress/hooks';

const createNonceMiddleware = ( nonce ) => ( options, next ) => {
const createNonceMiddleware = ( nonce ) => {
let usedNonce = nonce;

/**
* This is not ideal but it's fine for now.
*
Expand All @@ -17,31 +18,33 @@ const createNonceMiddleware = ( nonce ) => ( 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;
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,
};
}
if ( addNonceHeader ) {
// Do not mutate the original headers object, if any.
headers = {
...headers,
'X-WP-Nonce': usedNonce,
};
}

return next( {
...options,
headers,
} );
return next( {
...options,
headers,
} );
};
};

export default createNonceMiddleware;

0 comments on commit 6808261

Please sign in to comment.