Permission Check for REST API Endpoint Runs Twice?

Question

I’m making a plugin using the WP REST API, and everything seems to be working as expected. However, there is behavior I don’t understand. The authPermissionCheck() method is executed twice for each request before output is generated – first here and then here. It just seems inefficient. Does anyone understand why?

Here’s the relevant portion of my plugin code (stripped down):

class My_REST_Controller
{
    public function __construct()
    {
        add_action( 'rest_api_init', function()
        {
            $this->user = wp_get_current_user();

            register_rest_route( 'myplug/v1', '/auth', array(
                array(
                    'methods'  => WP_REST_Server::READABLE,
                    'callback' => array( $this, 'authenticate' ),
                    'permission_callback' => array( $this, 'authPermissionCheck' )
                )
            ));
        });
    }

    // This method is called twice when the
    // auth endpoint is hit. Why?
    public function authPermissionCheck()
    {
        if ( ! user_can( $this->user, 'read' ) ) {
            return new WP_Error( 'rest_forbidden', esc_html__(
                'No permission.', 'my-text-domain' ),
                array( 'status' => 401 )
            );
        }
        return false;
    }
}

--------------------------------------------------

>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="https://www.wptricks.com/question/permission-check-for-rest-api-endpoint-runs-twice/">

Permission Check for REST API Endpoint Runs Twice?</a>
0
, Shotster 2 months 0 Answers 48 views 0

Leave an answer