Adding relational data to the user model / collection in the ctx.state.user

I’ll provide three valid metods. I would recommend to get it inside controller at the first step.

1. Inside controller(recommended)

let { isp } = await strapi.query('user', 'users-permissions').findOne({ id: ctx.state.user.id }, ['isp']);
ctx.state.user.isp = isp;

2. By using policies(also recommended), will work the same as the controller method

Create a file under ./config/policies/includeUserRelations.js

With the following code:

module.exports = async (ctx, next) => {
  if (ctx.state.user) {
    let { isp } = await strapi.query('user', 'users-permissions').findOne({ id: ctx.state.user.id }, ['isp']);
    ctx.state.user.isp = isp;
  }
  return await next();
};

Now add that policy to your route where you want to get isp under ctx.state.user object.
Example:

[
{
      "method": "GET",
      "path": "/orders",
      "handler": "order.find",
      "config": {
        "policies": ["global::includeUserRelations"]
      }
    }
]

Check policies documentation if you want to create API scoped policy.


3. Using extensions(not recommended) - it will be hard to maintain future updates

Create a file under:
./extensions/users-permissions/config/policies/permissions.js

Copy inside it content from:
./node_modules/strapi-plugin-users-permissions/config/policies/permissions.js

Replace this code:
ctx.state.user = await strapi.plugins['users-permissions'].services.user.fetchAuthenticatedUser(id);

With this one:
ctx.state.user = await strapi.query('user', 'users-permissions').findOne({ id }, ['isp']);

4 Likes