alleyinteractive / alley-scripts

A collection of scripts and utilities for Alley projects.
https://alley-scripts.alley.dev/
6 stars 1 forks source link

PostPicker, usePostById, and usePost Don't Work for Users with Lower Permission Levels #620

Closed kevinfodness closed 5 months ago

kevinfodness commented 5 months ago

Description of the bug

If a user with a lower level of permission, like an author, attempts to edit a post that uses a PostPicker that references a post that they don't have permission to edit, the component will throw an error. This issue can be traced through usePostById to usePost and affects the PostPicker component and both hooks.

Why this happens:

On initial selection, the PostPicker uses the search endpoint to search for posts, which is publicly accessible. However, once the post is selected, the PostPicker gets information about the post using usePostById which calls usePost. usePost calls select('core').getEntityRecord('postType', postType, postId) which results in an apiFetch against the core endpoint for that post type, which notably includes ?context=edit. The addition of that parameter causes the REST API to serve a 403 response, because it knows who the user is, and knows that the user doesn't have edit rights to that post. However, in a PostPicker context, the user doesn't need edit rights to the post, it just needs to refer to it by ID. The same is likely true (although not necessarily always so) for usage of the usePostById and usePost hooks.

We should:

  1. Create a method of fetching information about posts that does not pass the edit context and make it the default behavior for both usePost and usePostById. An optional parameter could be passed to those hooks to fetch the edit context, but it would be opt-in.
  2. Ensure the PostPicker works for users without permissions to edit all posts (e.g., an Author referencing a post they did not create). By changing the context to not include edit, some information may not be available as part of the initial data fetch (e.g., I believe edit does some things for you, like expands the featured image from an ID reference to an object that contains information about the image, which would need to be a follow-up request if the featured image is used in the PostPicker).

Steps To Reproduce

  1. Create a post as one user.
  2. Log in as another user with Author permissions.
  3. Create a post that uses a PostPicker.
  4. Use the PostPicker to select the post created by the other user.
  5. Notice that the initial search works properly, but an error message is presented to the user once selected.

Additional Information

No response