Populating Users-Permission Relation in Strapi
Is it a bug?
Written on November 07, 2024 · 2 min read
Recently, I found an annoying bug(?) in Strapi where I create a collection type with Users-Permission relation. It doesn't show up on the API response even with ?populate=*
.
Steps to reproduce the behavior:
- Create a user in the Users-Permissions
- Create some other collection type and link it with user
- Enable public find permission on both
- Send a GET request to the
/users
with?populate=\*
- Response won't contain the relational field
Here's the temporary fix:
// path: src/extensions/users-permissions/strapi-server.js
module.exports = plugin => {
const sanitizeOutput = (user) => {
const {
password, resetPasswordToken, confirmationToken, ...sanitizedUser
} = user; // be careful, you need to omit other private attributes yourself
return sanitizedUser;
};
plugin.controllers.user.me = async (ctx) => {
if (!ctx.state.user) {
return ctx.unauthorized();
}
const user = await strapi.entityService.findOne(
'plugin::users-permissions.user',
ctx.state.user.id,
{ populate: ['role'] }
);
ctx.body = sanitizeOutput(user);
};
plugin.controllers.user.find = async (ctx) => {
const users = await strapi.entityService.findMany(
'plugin::users-permissions.user',
{ ...ctx.params, populate: ['role'] }
);
ctx.body = users.map(user => sanitizeOutput(user));
};
return plugin;
};
Wait until the Strapi server is restarted. Done!
Source: https://github.com/strapi/strapi/issues/11957#issuecomment-1001102421
This note is written by Diky Hadna — Software Engineer & Digital Nomad Mentor. Read my story and get in touch with me!