RestAPI Find Action Cannot Filter by User

System Information
  • Strapi Version: 4.9.0
  • Operating System: macOS Monterey (12.6.4)
  • Database: PostgreSQL
  • Node Version: 16.19.1
  • Yarn Version: 1.22.19

I have a relationship between a “User Profile” Content-Type and the “User” via the “Users Permission” Plugin. However I don’t appear to be able to filter by this plugin through the RestAPI, but the admin interface can.

I need to apply a filter to a request to ensure the Authenticated User does not retrieve records belonging to another user. To achieve this, I have updated the controller with the following:

import { factories } from "@strapi/strapi";

export default factories.createCoreController("api::user-profile.user-profile", {
    async find(ctx) {
        const {user} = ctx.state;

        ctx.query.filters = {
            ...ctx.query.filters,

            user: {
                username: {
                    $eq: user.username,
                }
            }
        };

        const response = await super.find(ctx);
        return response;
    }
});

When I test the request using an authenticated user’s token, it appears to ignore the user.username filter added to the ctx object. I’ve tested the filter through the admin interface and it works as expected.

Why doesn’t it work through the RestAPI?

I would recomand doing an $and = […ctx.query.filters, user { username { $eq: user.username}}}] that way it can never be overwriten