all repos — caroster @ f23ba3d49ddd49492d4bb06c4a345acf3ec0235c

[Octree] Group carpool to your event https://caroster.io

🔧 Set permissions automatically
Tim Izzo tim@octree.ch
Wed, 01 Jul 2020 15:12:20 +0200
commit

f23ba3d49ddd49492d4bb06c4a345acf3ec0235c

parent

a35bb0c7f225b13d8268326ad157f3a3b5215b99

2 files changed, 84 insertions(+), 2 deletions(-)

jump to
M config/functions/bootstrap.jsconfig/functions/bootstrap.js

@@ -1,4 +1,6 @@

-'use strict'; +"use strict"; + +const permissions = require("../permissions.json"); /** * An asynchronous bootstrap function that runs before

@@ -10,4 +12,61 @@ *

* See more details here: https://strapi.io/documentation/v3.x/concepts/configurations.html#bootstrap */ -module.exports = () => {}; +module.exports = async () => { + /** + * Set permissions + */ + + // For each role, set permissions + const roles = Object.keys(permissions.roles); + await Promise.all( + roles.map(async (roleType) => { + // Get role entity in Strapi db + const role = await strapi.query("role", "users-permissions").findOne({ + type: roleType, + }); + // If role doesn't exist, skip + if (!role) return []; + + // Enable or create permissions for each roles, controllers and actions + const perms = permissions.roles[roleType]; + return perms.map(({ type, controllers }) => + controllers.map(({ name: controller, actions }) => + actions.map(async (action) => { + const existingPerm = await strapi + .query("permission", "users-permissions") + .findOne({ + role: role.id, + type, + controller, + action, + }); + if (!!existingPerm) { + if (existingPerm.enabled) return false; // If permission already enabled, skip + strapi.log.info( + `Enable permission ${type}.${controller}.${action} for role ${roleType}.` + ); + return strapi + .query("permission", "users-permissions") + .update( + { role: role.id, type, controller, action }, + { enabled: true } + ); + } else { + strapi.log.info( + `Create permission ${type}.${controller}.${action} for role ${roleType}.` + ); + return strapi.query("permission", "users-permissions").create({ + role: role.id, + type, + controller, + action, + enabled: true, + }); + } + }) + ) + ); + }) + ); +};
A config/permissions.json

@@ -0,0 +1,23 @@

+{ + "roles": { + "public": [ + { + "type": "application", + "controllers": [ + { + "name": "car", + "actions": ["create", "delete", "find", "findone", "update"] + }, + { + "name": "event", + "actions": ["create", "findone", "update"] + }, + { + "name": "page", + "actions": ["find", "findone"] + } + ] + } + ] + } +}