Custom policy policyContext.state.user undefined

System Information
  • Strapi Version: 4.5.2
  • Operating System: MacOs Ventura
  • Database: MySQL 7.4.21
  • Node Version: v16.18.0
  • NPM Version: 8.19.2
  • Yarn Version: 1.22.19

Hi, I want to create global custom policies for some routes in the API.

After reading the doc… I created policy withe strapi generate CLI and use the base example of the doc.

My route file :

"use strict";

/**
 * product router
 */

const { createCoreRouter } = require("@strapi/strapi").factories;
module.exports = createCoreRouter("api::product.product", {
  prefix: "",
  only: ["find"],
  except: [],
  config: {
    find: {
      auth: false,
      policies: ["global::handle-delete-permission"],
      middlewares: [],
    },
    findOne: {},
    create: {},
    update: {},
    delete: {},
  },
});

My policy file ( I tried the exemple in the documentation )

'use strict';

/**
 * `handle-delete-permission` policy
 */

module.exports = (policyContext, config, { strapi }) => {

  //console.log('policyContext', policyContext.state.user);
  if (policyContext.state.user) { // if a session is open
    // go to next policy or reach the controller's action
    return true;
  }

  return false;
};

I can access to policyContext, but policyContext.state.user is undefined…
( I call the api with my auth bearer token )

I do something wrong, but I can’t find out what it is ?

Thanks !

I solved it.

I found what i was doing wrong, in my route config my i had auth: false, so even if i was submitting the request with my bearer token, the request was not handling the auth and was not populate the policyContext.state.user details… Simply remove the auth: false and it’s working as expected !

Hope it can be useful for someone ! :+1::slightly_smiling_face:

The new route file with the correction :

"use strict";

/**
 * product router
 */

const { createCoreRouter } = require("@strapi/strapi").factories;
module.exports = createCoreRouter("api::product.product", {
  prefix: "",
  only: ["find"],
  except: [],
  config: {
    find: {
      policies: ["global::handle-delete-permission"],
      middlewares: [],
    },
    findOne: {},
    create: {},
    update: {},
    delete: {},
  },
});

1 Like