• Resolved lucasbustamante

    (@lucasbustamante)


    I’m using the following code to assert user can read a product:

    $pto = get_post_type_object('product');
    return current_user_can($pto->cap->read_post, $product->get_id());

    However, this does not work for guests. I have tried $pto->cap->read as well.

    I was using \WC_Product::is_visible() before, but I was told it was a security breach.

    What is the correct way of asserting a user can read a product in WooCommerce?

Viewing 4 replies - 1 through 4 (of 4 total)
  • jessepearson

    (@jessepearson)

    Automattic Happiness Engineer

    @lucasbustamante I am afraid I am not following with what you are trying to accomplish here. By default all products are available to all users. What is the end result you are looking for?

    Thread Starter lucasbustamante

    (@lucasbustamante)

    Hi Jesse,

    I have a plugin that interacts with WooCommerce using a REST endpoint that receives a product ID as a parameter. As part of the permission callback of this endpoint, it asserts that the person requesting that product ID has access to view it.

    current_user_can always returns false for guests, so I can’t check “read_post” capability. If not that, what is the correct way to assert that a person can read a product?

    I am currently checking if product is visible and has no password, but I’m not sure if that covers all usage cases, and I’m trying to find the best practice for that scenario.

    Code I’m currently using:
    return $product->is_visible() && empty(get_post($product->get_id())->post_password);

    Full source code, if you’re curious:
    https://github.com/Luc45/WooCommerce-Correios-Calculo-de-Frete-na-Pagina-do-Produto/blob/master/src/Rest.php#L70

    jessepearson

    (@jessepearson)

    Automattic Happiness Engineer

    @lucasbustamante The tests you are doing seem to be all that is needed, is_visible() does a lot of checks to see if the product should be able to be viewed or not. Then checking to see if it has a password would be the last thing I would believe is needed.

    Kenin

    (@kbassart)

    Automattic Happiness Engineer

    We haven’t heard back from you in a while, so I’m going to mark this as resolved – if you have any further questions, you can start a new thread.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Correct way to assert user can read product?’ is closed to new replies.