Automattic\WooCommerce\Admin\Features\Fulfillments
OrderFulfillmentsRestController::check_permission_for_fulfillments
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() OrderFulfillmentsRestController::check permission for fulfillments code WC 10.8.1
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.
// Guest order fulfillments are rendered server-side via templates, so they don't need REST API access.
// The get_current_user_id() > 0 check prevents unauthenticated users from accessing guest orders
// where both get_current_user_id() and get_customer_id() would return 0.
if ( get_current_user_id() > 0 && 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() )
);
}