Automattic\WooCommerce\Internal\Fulfillments

OrderFulfillmentsRestController::check_permission_for_fulfillmentsprotectedWC 1.0

Permission check for REST API endpoints, given the request method. For all fulfillments methods that have an order_id, we need to be sure the user has permission to view the order. For all other methods, we check if the user is logged in as admin and has the required capability.

Method of the class: OrderFulfillmentsRestController{}

No Hooks.

Returns

true|false|\WP_Error. True if the current user has the capability, otherwise an "Unauthorized" error or False if no error is available for the request method.

Usage

// protected - for code of main (parent) or child class
$result = $this->check_permission_for_fulfillments( $request );
$request(WP_REST_Request) (required)
The request for which the permission is checked.

OrderFulfillmentsRestController::check_permission_for_fulfillments() code WC 10.3.3

protected function check_permission_for_fulfillments( WP_REST_Request $request ) {
	// Fetch the order first if there's an order_id in the request.
	$order = null;
	if ( $request->has_param( 'order_id' ) ) {
		$order_id = (int) $request->get_param( 'order_id' );
		$order    = wc_get_order( $order_id );

		if ( ! $order ) {
			return new \WP_Error(
				'woocommerce_rest_order_invalid_id',
				esc_html__( 'Invalid order ID.', 'woocommerce' ),
				array( 'status' => esc_attr( WP_Http::NOT_FOUND ) )
			);
		}
	}

	// Check if the user is logged in as admin, and has the required capability.
	// Admins who can manage WooCommerce can view all fulfillments.
	if ( current_user_can( 'manage_woocommerce' ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown
		return true;
	}

	// Check if the order exists, and if the current user is the owner of the order, and the request is a read request.
	// We allow this because we need to render the order fulfillments on the customer's order details and order tracking pages.
	// But they will be only able to view them, not edit.
	if ( get_current_user_id() === $order->get_customer_id() && WP_REST_Server::READABLE === $request->get_method() ) {
		return true;
	}

	// Return an error related to the request method.
	$error_information = $this->get_authentication_error_by_method( $request->get_method() );

	if ( is_null( $error_information ) ) {
		return false;
	}

	return new \WP_Error(
		$error_information['code'],
		$error_information['message'],
		array( 'status' => rest_authorization_required_code() )
	);
}