How to Add Middleware in Strapi to Filter core "Find" Method Results by Owner?

136 Views Asked by At

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.

1

There are 1 best solutions below

0
Murat Çorlu On

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