Prevent user to modify records they do not own

System Information
  • Strapi Version: V4
  • Database: PostreSQL

Hi there,

I am new in web development and I am building an app with Strapi and Refine. In this application, users can create books they own and reserve books owned by others. I would like to prevent a user to modify books owned by others, and the same for the ‘reservations’ collection, expect for users part of the ‘admin’ role.

Could someone give me an hint how to do that?

Thanks in advance,
Pierre

Assuming you would like to protect the API endpoint PUT /api/books/:id so that it returns 403 Forbidden if the book doesn’t belong to the user.

The process to implement this would be:

  1. Wrap the update core controller. See the example for find here.
  2. As part of your wrapper, first retrieve the book, e.g using the entityService (see example here). Then check for the createdBy id of the book. If it doesn’t match the id of the user making the request (e.g found in ctx.state.user.id), simply return a Forbidden response (e.g using ctx.forbidden).

Another option would be implementing the above in a middleware instead of by wrapping the controller.

2 Likes

Thanks very much for your response. I will have a look.