Skip to content

Instantly share code, notes, and snippets.

@loicgeek
Last active May 31, 2021 17:13
Show Gist options
  • Save loicgeek/691a4833279361d8d8ff6d6410cd10d5 to your computer and use it in GitHub Desktop.
Save loicgeek/691a4833279361d8d8ff6d6410cd10d5 to your computer and use it in GitHub Desktop.
Strapi isOwner policy (non static)
/*File /config/policies/isOwner.js */
module.exports = async (ctx, next) => {
if (ctx.state.user) {
const controller = ctx.request.route.controller;
const o = `${strapi.config.ownmap[controller]}.id`;
var data = {
id: ctx.params.id
};
data[o] = ctx.state.user.id;
const [owner] = await strapi.services[controller].find(data);
if (!owner) {
return ctx.unauthorized(`You don't have access to this entry`);
}
return await next();
}
};
/* file /config/ownmap.js */
/* this file contain a json to map all controller with the corresponding field */
/* For example if we have a Restaurant entity and and the owner in that entity is user then we ll map as follows: */
{
"ownmap": {
"restaurant": "user",
"job": "owner"
}
}
/* File /api/restaurant/config/routes.json */
.....
{
"method": "PUT",
"path": "/restaurants/:id",
"handler": "restaurant.update",
"config": {
"policies": [
"global::isOwner" //USAGE
]
}
},
{
"method": "DELETE",
"path": "/restaurants/:id",
"handler": "restaurant.delete",
"config": {
"policies": [
"global::isOwner" //USAGE
]
}
},
....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment