From cde40c918f7c7ba573fe27f5b7877ad3239c3e97 Mon Sep 17 00:00:00 2001 From: "Dominik Schilling (ocean90)" Date: Sun, 18 Mar 2018 17:03:20 +0000 Subject: [PATCH] REST API JS Client: Extend custom nonce functionality to collections. This brings the improved nonce handling from [41553] to collections to remove the direct `wpApiSettings.nonce` dependency. Props adamsilverstein, ocean90, swissspidy. Fixes #43265. git-svn-id: https://develop.svn.wordpress.org/trunk@42851 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/js/wp-api.js | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/src/wp-includes/js/wp-api.js b/src/wp-includes/js/wp-api.js index d796ddc475..fc9750fa70 100644 --- a/src/wp-includes/js/wp-api.js +++ b/src/wp-includes/js/wp-api.js @@ -990,18 +990,28 @@ var beforeSend, success, self = this; - options = options || {}; - beforeSend = options.beforeSend; + options = options || {}; - // If we have a localized nonce, pass that along with each sync. - if ( 'undefined' !== typeof wpApiSettings.nonce ) { + if ( _.isFunction( model.nonce ) && ! _.isUndefined( model.nonce() ) && ! _.isNull( model.nonce() ) ) { + beforeSend = options.beforeSend; + + // Include the nonce with requests. options.beforeSend = function( xhr ) { - xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); + xhr.setRequestHeader( 'X-WP-Nonce', model.nonce() ); if ( beforeSend ) { return beforeSend.apply( self, arguments ); } }; + + // Update the nonce when a new nonce is returned with the response. + options.complete = function( xhr ) { + var returnedNonce = xhr.getResponseHeader( 'X-WP-Nonce' ); + + if ( returnedNonce && _.isFunction( model.nonce ) && model.nonce() !== returnedNonce ) { + model.endpointModel.set( 'nonce', returnedNonce ); + } + }; } // When reading, add pagination data. @@ -1405,6 +1415,13 @@ return new loadingObjects.models[ modelClassName ]( attrs, options ); }, + // Track nonces at the Endpoint level. + nonce: function() { + return routeModel.get( 'nonce' ); + }, + + endpointModel: routeModel, + // Include a reference to the original class name. name: collectionClassName, @@ -1432,6 +1449,13 @@ return new loadingObjects.models[ modelClassName ]( attrs, options ); }, + // Track nonces at the Endpoint level. + nonce: function() { + return routeModel.get( 'nonce' ); + }, + + endpointModel: routeModel, + // Include a reference to the original class name. name: collectionClassName,