diff --git a/inc/REST/RemoteDataController.php b/inc/REST/RemoteDataController.php index 21667bd71..396d2a02d 100644 --- a/inc/REST/RemoteDataController.php +++ b/inc/REST/RemoteDataController.php @@ -78,7 +78,22 @@ public static function execute_queries( WP_REST_Request $request ): array|WP_Err ); } - public static function permission_callback(): bool { - return true; + /** + * Permission callback for the remote data endpoint. + * + * @param WP_REST_Request $request The REST request. + * + * @return bool|WP_Error Returns status of user permission, otherwise WP_Error. + */ + public static function permission_callback( WP_REST_Request $request ): bool|WP_Error { + $post_id = (int) $request->get_param( 'post_id' ); + if ( $post_id <= 0 ) { + return new WP_Error( + 'rest_post_invalid_id', + __( 'Invalid post ID.' ), + array( 'status' => 404 ) + ); + } + return current_user_can( 'edit_post', $post_id ); } } diff --git a/src/blocks/remote-data-container/hooks/useRemoteData.ts b/src/blocks/remote-data-container/hooks/useRemoteData.ts index 1b5d30fa9..7b5daa2d4 100644 --- a/src/blocks/remote-data-container/hooks/useRemoteData.ts +++ b/src/blocks/remote-data-container/hooks/useRemoteData.ts @@ -1,4 +1,6 @@ import apiFetch from '@wordpress/api-fetch'; +import { select } from '@wordpress/data'; +import { store as editorStore } from '@wordpress/editor'; import { useEffect, useState } from '@wordpress/element'; import { REMOTE_DATA_REST_API_URL } from '@/blocks/remote-data-container/config/constants'; @@ -177,6 +179,9 @@ export function useRemoteData( { } async function fetch( inputs: RemoteDataQueryInput[] ): Promise< void > { + const { getCurrentPostId } = select( editorStore ); + const postId = getCurrentPostId(); + // If there are no inputs, there is nothing to fetch. Empty query inputs // must be represented by an empty object, e.g. `[ {} ]`. if ( 0 === inputs.length ) { @@ -192,6 +197,7 @@ export function useRemoteData( { const requestData: RemoteDataApiRequest = { block_name: blockName, + post_id: postId ?? null, query_key: queryKey, query_inputs: inputs, }; diff --git a/types/remote-data.d.ts b/types/remote-data.d.ts index 0913adf13..b3d2ab28d 100644 --- a/types/remote-data.d.ts +++ b/types/remote-data.d.ts @@ -95,6 +95,7 @@ interface RemoteDataInnerBlockAttributes { interface RemoteDataApiRequest { block_name: string; + post_id: number | string | null; query_inputs: RemoteDataQueryInput[]; query_key: string; }