AuthorizesPushNotificationRequests.php
52 lines
| 1 | <?php |
| 2 | |
| 3 | declare( strict_types = 1 ); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Internal\PushNotifications\Traits; |
| 6 | |
| 7 | defined( 'ABSPATH' ) || exit; |
| 8 | |
| 9 | use Automattic\WooCommerce\Internal\PushNotifications\PushNotifications; |
| 10 | use WP_Error; |
| 11 | use WP_REST_Request; |
| 12 | |
| 13 | /** |
| 14 | * Shared "is this caller an authenticated push-notifications user?" check for |
| 15 | * REST controllers in the PushNotifications module. |
| 16 | * |
| 17 | * Implementing classes must extend {@see \Automattic\WooCommerce\Internal\RestApiControllerBase} |
| 18 | * so that `check_permission()` is available. |
| 19 | */ |
| 20 | trait AuthorizesPushNotificationRequests { |
| 21 | /** |
| 22 | * Checks the user is authenticated, the push notifications module is |
| 23 | * enabled, and the user holds at least one role allowed to interact with |
| 24 | * push notifications. |
| 25 | * |
| 26 | * @param WP_REST_Request $request The request object. |
| 27 | * @phpstan-param WP_REST_Request<array<string, mixed>> $request |
| 28 | * @return bool|WP_Error |
| 29 | */ |
| 30 | public function authorize_as_authenticated( WP_REST_Request $request ) { |
| 31 | if ( ! get_current_user_id() ) { |
| 32 | return new WP_Error( |
| 33 | 'woocommerce_rest_cannot_view', |
| 34 | __( 'Sorry, you are not allowed to do that.', 'woocommerce' ), |
| 35 | array( 'status' => rest_authorization_required_code() ) |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | if ( ! wc_get_container()->get( PushNotifications::class )->should_be_enabled() ) { |
| 40 | return false; |
| 41 | } |
| 42 | |
| 43 | $has_valid_role = array_reduce( |
| 44 | PushNotifications::ROLES_WITH_PUSH_NOTIFICATIONS_ENABLED, |
| 45 | fn ( $carry, $role ) => $this->check_permission( $request, $role ) === true ? true : $carry, |
| 46 | false |
| 47 | ); |
| 48 | |
| 49 | return $has_valid_role ? true : false; |
| 50 | } |
| 51 | } |
| 52 |