REST API: Permit access to the themes controller if user can edit any post type.

Check a more exhaustive list of post type editing caps beyond "edit_post" to ensure custom user roles with access to to specific post types may still use block editor functionality depending on theme features.

Props miyauchi, TimothyBlynJacobs.
Fixes #46723.


git-svn-id: https://develop.svn.wordpress.org/trunk@47361 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
K. Adam White 2020-02-25 15:18:19 +00:00
parent a0ac0ff13d
commit b5190458fe
2 changed files with 34 additions and 7 deletions

View File

@ -58,15 +58,21 @@ class WP_REST_Themes_Controller extends WP_REST_Controller {
* @return true|WP_Error True if the request has read access for the item, otherwise WP_Error object.
*/
public function get_items_permissions_check( $request ) {
if ( ! is_user_logged_in() || ! current_user_can( 'edit_posts' ) ) {
return new WP_Error(
'rest_user_cannot_view',
__( 'Sorry, you are not allowed to view themes.' ),
array( 'status' => rest_authorization_required_code() )
);
if ( current_user_can( 'edit_posts' ) ) {
return true;
}
return true;
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
return true;
}
}
return new WP_Error(
'rest_user_cannot_view',
__( 'Sorry, you are not allowed to view themes.' ),
array( 'status' => rest_authorization_required_code() )
);
}
/**

View File

@ -155,6 +155,15 @@ class WP_Test_REST_Themes_Controller extends WP_Test_REST_Controller_Testcase {
$this->assertEqualSets( $fields, array_keys( $data[0] ) );
}
/**
* @ticket 46723
*/
public function test_get_items_logged_out() {
wp_set_current_user( 0 );
$response = self::perform_active_theme_request();
$this->assertErrorResponse( 'rest_user_cannot_view', $response, 401 );
}
/**
* An error should be returned when the user does not have the edit_posts capability.
*
@ -166,6 +175,18 @@ class WP_Test_REST_Themes_Controller extends WP_Test_REST_Controller_Testcase {
$this->assertErrorResponse( 'rest_user_cannot_view', $response, 403 );
}
/**
* @ticket 46723
*/
public function test_get_item_single_post_type_cap() {
$user = self::factory()->user->create_and_get();
$user->add_cap( 'edit_pages' );
wp_set_current_user( $user->ID );
$response = self::perform_active_theme_request();
$this->assertEquals( 200, $response->get_status() );
}
/**
* Test an item is prepared for the response.
*