Last active
May 31, 2021 17:13
-
-
Save loicgeek/691a4833279361d8d8ff6d6410cd10d5 to your computer and use it in GitHub Desktop.
Strapi isOwner policy (non static)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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(); | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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