0

I'm currently trying to add middleware in Strapi so that when a user utilizes the core "find" method on a collection, they only see records they own.

I've already implemented a middleware that works for "update" and "delete" methods based on this documentation. However, I can't seem to adapt this example for the "find" method as I can't manipulate the query.

Of course, I have the option to create a custom route to accomplish this, but it would be much more efficient to apply this to existing routes for easier maintenance.

Any insights on how to achieve this?

I already tried to get the result of the controller using await next(); to then filter manually the result; but there aren't all the necessary field to filter the data like that, and I don't want theses field to appears to the user.

2
  • Hi, maybe this may help you stackoverflow.com/questions/75390415/… Commented Oct 30, 2023 at 21:50
  • Your basic approach is to override ctx.query object, before await next, and append owner to it query. E.g ctx.query = {…ctx.query, filter: { owner: { id: user.id }}}; Commented Oct 30, 2023 at 21:52

2 Answers 2

3

I could manage to write an own-records-only middleware that filters records that only belongs to the signed in user, like below (file in src/middlewares):

/**
 * `own-records-only` middleware
 */

module.exports = ({ field = 'user' }, { }) => {
  return async (ctx, next) => {
    ctx.query.filters = {
      ...ctx.query.filters,
      [field]: {
        id: {
          $eq: ctx.state.user.id
        }
      }
    };

    await next();
  };
};

Usage (in a route definition):

const { createCoreRouter } = require('@strapi/strapi').factories;

module.exports = createCoreRouter('api::site.site', {
  config: {
    find: {
      middlewares: [
        { name: 'global::own-records-only', config: { field: 'user' } }
      ],
    },
  },
});

But for me there was a catch: user field, that I want to use for filtering was a relation to "users & permissions" plugin. To be able to use a field related to user model, you need to give find permission to the Role that you use for the requests, in "Settings -> Users & Permissions Plugin -> Roles -> [Role]"

I hope this help.

Note: I'm talking here with Strapi v4.20

Sign up to request clarification or add additional context in comments.

1 Comment

This was my massive gotcha. I needed to add find permissions to my field, otherwise I get a 400 status response saying that the key is invalid. Thanks a lot!
0

Unfortunately the best approach is to override the controller(s).

Follow the following example:


/**
 *  task controller
 */

const { createCoreController } = require('@strapi/strapi').factories;

const ownerKey = "owner";

export default factories.createCoreController(
  "api::event.event",
  ({ strapi }) => ({
    async find(ctx) {
      const { filters } = ctx.query;

      ctx.query = {
        ...ctx.query,
        filters: { ...filters, [ownerKey]: { $eq: ctx.state.user.id } },
      };

      const entities = await strapi.entityService?.findMany(
        "api::event.event",
        ctx.query
      );

      return this.transformResponse(entities);
    },
}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.