Skip to content

Instantly share code, notes, and snippets.

@8byr0
Created November 11, 2019 08:02
Show Gist options
  • Save 8byr0/19968388ab9e2db7aa06f59c4964c6ba to your computer and use it in GitHub Desktop.
Save 8byr0/19968388ab9e2db7aa06f59c4964c6ba to your computer and use it in GitHub Desktop.
Strapi policy: add and use `createdBy` field to models
'use strict';
/**
* `isCreatedBy` policy.
* group `administrator` must be created from interface
*/
module.exports = async (ctx, next, args) => {
const { id } = ctx.state.user;
const role = ctx.state.user.role.type
if (role !== "administrator") {
ctx.query.createdBy = id;
}
await next();
if (Array.isArray(ctx.response.body) && role !== 'administrator') {
ctx.response.body = ctx.response.body.filter((elt) => {
if (!!!elt.createdBy) {
// createdBy not set, do not return document
return false
}
return elt.createdBy && (elt.createdBy.id.toString() === id)
});
}
else {
if (role !== "administrator") {
if (!!!ctx.response.body.createdBy) {
// createdBy does not exist, raise exception
return ctx.unauthorized("You are not allowed to perform this action.");
}
const createdBy = ctx.response.body.createdBy.id;
if (createdBy !== id) {
return ctx.unauthorized("You are not allowed to perform this action.");
}
}
}
};
// Add setCreatedBy to POST (creation)
// Add isCreatedBy to other routes
{
"routes": [
{
"method": "GET",
"path": "/model",
"handler": "Model.find",
"config": {
"policies": [
"global.isCreatedBy"
]
}
},
{
"method": "GET",
"path": "/model/count",
"handler": "Model.count",
"config": {
"policies": [
"global.isCreatedBy"
]
}
},
{
"method": "GET",
"path": "/model/:id",
"handler": "Model.findOne",
"config": {
"policies": [
"global.isCreatedBy"
]
}
},
{
"method": "POST",
"path": "/model",
"handler": "Model.create",
"config": {
"policies": [
"global.setCreatedBy"
]
}
},
{
"method": "PUT",
"path": "/model/:id",
"handler": "Model.update",
"config": {
"policies": [
"global.isCreatedBy"
]
}
},
{
"method": "DELETE",
"path": "/model/:id",
"handler": "Model.delete",
"config": {
"policies": [
"global.isCreatedBy"
]
}
}
]
}
'use strict';
/**
* `setCreatedBy` policy.
*/
module.exports = async (ctx, next) => {
const { id } = ctx.state.user;
const { body } = ctx.request;
body.createdBy = id.toString();
await next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment