Last active
December 13, 2020 12:27
-
-
Save modjke/237ab3b4460db6d1f86bd1a523766b5a to your computer and use it in GitHub Desktop.
Enabling certain permissions at stratup in strapi 3
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
'use strict'; | |
module.exports = async () => { | |
const publicRole = await getRoleByName('Public') | |
grantPermissions(publicRole, 'application', 'images', ['upload', 'remove']) // upload, remove in 'images' controller | |
grantPermissions(publicRole, 'application', 'project') // any action in 'project' controller | |
}; | |
async function getRoleByName(name) { | |
return strapi.query('role', 'users-permissions').findOne({ name }, []) | |
} | |
async function getPermissions(role, permissionType, controller, actions = null) { | |
const permissionQuery = strapi.query('permission', 'users-permissions') | |
const permissionRequest = { | |
_limit: 1000, | |
role: role.id, | |
type: permissionType, | |
controller: controller | |
} | |
if (actions) { | |
permissionRequest.action_in = Array.isArray(actions) ? actions : [actions] | |
} | |
return permissionQuery.find(permissionRequest, []) | |
} | |
async function grantPermissions(role, permissionType, controller, actions) { | |
if (actions && !Array.isArray(actions)) { | |
actions = [ actions ] | |
} | |
strapi.log.info(`Setting '${controller}' [${actions ? actions.join(', ') : '*'}] permissions for '${role.name}'`) | |
const permissionQuery = strapi.query('permission', 'users-permissions') | |
const permissions = await getPermissions(role, permissionType, controller, actions) | |
if (permissions.length === 0) { | |
throw new Error(`Error enabling permissions: ${role.name}, ${permissionType}, ${controller}, ${actions}`) | |
} | |
for (const { id } of permissions) { | |
await permissionQuery.update({ id }, { enabled: true }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment