Strapi v4 Middleware ctx.state.user

Hello , i am trying to implement an RBAC feature.

My approach is,

  • I ll create a Content Type , called RBAC where i 'll store user_id, conent_type and action type. (that the user can perform)
  • Create a global middleware where it calls the RBAC contenttype and appends to the ctx the rbac information.
  • Create policies to each route accordingly.

I`ve created my global middleware. registered in the /config/middleware.js. (at the end)

Issue:
I cannot access the current user (if it exists) in the middleware.
ctx.state.user = {} but in the controller i have that information.

Any suggestions how i can tackle this? It would be wiser for me if can someone provide me with a Request Life Cycle, so i will know in the future, where for example, the user gets appended in the ctx (and by what) . With this i think will help me (and other devs) solve issues on our own :wink:

Thank you in advance

For anyone looking for how to get the user inside the Middleware.

I am getting the Id from the token and proceed with custom actions

Hi @MiTs can you please share the code from your middleware where you getting the current user?

@idc-dev_idc-dev
My sincere apologies for the delay,
got my middleware.


return async (ctx, next) => {
strapi.log.debug(‘We are inside the middleware’);
if (ctx.request && ctx.request.header && ctx.request.header.authorization) {

    const {id} = await strapi.plugins['users-permissions'].services.jwt.getToken(ctx);
    console.log('The id is.' + id);

}

4 Likes