禁止用户使用 Woocommerce API

问题描述 投票:0回答:1

我为用户创建了一个自定义复选框,如果选中该框,则会阻止他们使用 Woocommerce API。但是,如果选中该框,用户仍然可以使用该 API。我正在使用的过滤器和代码:

add_filter('woocommerce_rest_pre_dispatch', 'restrict_api_access_based_on_user_meta', 10, 3);

function restrict_api_access_based_on_user_meta($result, $server, $request) {
    // Check if the request is for the WooCommerce products endpoint
    if (strpos($request->get_route(), '/wc/v3/products') !== false) {
        // Retrieve user ID from the authentication information
        $user_id = apply_filters('determine_current_user', null);
        
        // Check if the user is authenticated and retrieve the 'disable_account_api' meta value
        if ($user_id) {
            $disable_account_api = get_user_meta($user_id, 'disable_account_api', true);

            // If 'disable_account_api' is set to "yes", deny access
            if ($disable_account_api === 'yes') {
                return new WP_Error(
                    'api_disabled',
                    __('API access has been disabled for this account.', 'woocommerce'),
                    array('status' => 403)
                );
            }
        }
    }
    return $result;
}

  

编辑user.php页面

thats custom checkbox

php wordpress woocommerce woocommerce-rest-api
1个回答
0
投票

我认为 woocommerce_rest_pre_dispatch 钩子不存在,您可以使用rest_pre_dispatch,但这会阻止所有 REST API。要仅限制 woocommerce REST API,您可以使用钩子 woocommerce_rest_check_permissions。

下面是根据meta值限制用户的代码

add_filter('woocommerce_rest_check_permissions', 'restrict_woocommerce_api_access', 10, 4);

function restrict_woocommerce_api_access($permission, $context, $object_id, $post_type) {
    // Get the current user ID
    $user = wp_get_current_user();
    $user_id = $user->ID;

    // Check if the user is authenticated and if the user meta restricts API access
    if ($user_id) {
        $disable_account_api = get_user_meta($user_id, 'disable_account_api', true);

        // If 'disable_account_api' is set to "yes", deny access to WooCommerce API
        if ($disable_account_api === 'yes') {
            return new WP_Error(
                'woocommerce_rest_forbidden',
                __('API access has been disabled for this account.', 'woocommerce'),
                array('status' => 403)
            );
        }
    }

    // Return the original permission if no restriction is needed
    return $permission;
}

该函数检查当前用户是否将disable_account_api元设置为“yes”。如果是这样,它会返回 WP_Error 以阻止对 WooCommerce API 的访问,并显示 403 禁止状态

© www.soinside.com 2019 - 2024. All rights reserved.