-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Description
Description
The @wordpress/core-data
module provides a selector canUser( action, resource, id )
that can interrogate whether a user has permission to perform the given CRUD action for the given resource and optionally a specific record.
For example, to check whether the user can update a page
with the id of 5
, you can perform the following check.
select( 'core' ).canUser( 'update', 'pages', 5 )
Unfortuantely, this method only supports resources that are in the wp/v2
namespace. Additionally, it requires you to know the final REST API path. Typically, however, only an entity kind
and name
are known.
There currently exists a canUserEntityRecord
selector, but it is only a wrapper for canUser
and does not Post Type entity records. Additionally, it only supports Post Types that have the wp/v2
namespace which is not a requirement since WP 5.9.
gutenberg/packages/core-data/src/selectors.ts
Lines 996 to 1009 in 1d778aa
export function canUserEditEntityRecord( | |
state: State, | |
kind: string, | |
name: string, | |
recordId: EntityRecordKey | |
): boolean | undefined { | |
const entityConfig = getEntityConfig( state, kind, name ); | |
if ( ! entityConfig ) { | |
return false; | |
} | |
const resource = entityConfig.__unstable_rest_base; | |
return canUser( state, 'update', resource, recordId ); | |
} |
I think canUserEntityRecord
should be adapted to actually perform the permission handling logic utilizing the baseURL
property of the entity config. Then canUser
would be deprecated.
Step-by-step reproduction instructions
- Register a custom post type with a custom namespace.
register_post_type( 'custom-ns', [
'public' => true,
'show_in_rest' => true,
'rest_namespace' => 'my/namespace',
'supports' => [ 'editor', 'title', 'custom-fields' ],
] );
- Call the
canUser
selector via the browser console.
wp.data.select('core').canUser('create', 'custom-ns');
Screenshots, screen recording, code snippet
No response
Environment info
No response
Please confirm that you have searched existing issues in the repo.
Yes
Please confirm that you have tested with all plugins deactivated except Gutenberg.
Yes