Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nonce Middleware: Wrap the nonce middleware function into it's own function. #11347

Merged
merged 1 commit into from
Nov 1, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;