wc_rest_check_user_permissions()WC 2.6.0

Check permissions of users on REST API.

Returns

true|false.

Usage

wc_rest_check_user_permissions( $context, $object_id );
$context(string)
Request context.
Default: 'read'
$object_id(int)
User ID.

Changelog

Since 2.6.0 Introduced.
Since 9.4.0 Became multisite aware. The function now considers whether the user belongs to the current site.

wc_rest_check_user_permissions() code WC 10.3.6

function wc_rest_check_user_permissions( $context = 'read', $object_id = 0 ) {
	$contexts = array(
		'read'   => 'list_users',
		'create' => 'create_customers',
		'edit'   => 'edit_users',
		'delete' => 'delete_users',
		'batch'  => 'promote_users',
	);

	// Check to allow shop_managers to manage only customers.
	if ( in_array( $context, array( 'edit', 'delete' ), true ) && wc_current_user_has_role( 'shop_manager' ) ) {
		$permission                  = false;
		$user_data                   = get_userdata( $object_id );
		$shop_manager_editable_roles = apply_filters( 'woocommerce_shop_manager_editable_roles', array( 'customer' ) );

		if ( isset( $user_data->roles ) ) {
			$can_manage_users = array_intersect( $user_data->roles, array_unique( $shop_manager_editable_roles ) );

			// Check if Shop Manager can edit customer or with the is same shop manager.
			if ( 0 < count( $can_manage_users ) || intval( $object_id ) === intval( get_current_user_id() ) ) {
				$permission = current_user_can( $contexts[ $context ], $object_id );
			}
		}
	} else {
		$permission = current_user_can( $contexts[ $context ], $object_id );
	}

	// Possibly revoke $permission if the user is 'out of bounds' from a multisite-network perspective.
	if ( $permission && ! Users::get_user_in_current_site( $object_id ) ) {
		$permission = false;
	}

	/**
	 * Provides an opportunity to override the permission check made before acting on an object in relation to
	 * REST API requests.
	 *
	 * @since 2.6.0
	 *
	 * @param bool   $permission  If we have permission to act on this object.
	 * @param string $context     Describes the operation being performed: 'read', 'edit', 'delete', etc.
	 * @param int    $object_id   Object ID. This could be a user ID, order ID, post ID, etc.
	 * @param string $object_type Type of object ('user', 'shop_order', etc) for which checks are being made.
	 */
	return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, 'user' );
}