Assign permissions to admin users in bootstrap

System Information
  • Strapi Version: 4.11.7
  • Operating System: debian
  • Database: sqlite
  • Node Version: v16.19.1
  • NPM Version: 8.18.0
  • Language: Typescript

Hey everyone, I need to generate a set of roles on server start and then assign them some default permissions. I have the role generation half working, but am running into issues adding the permissions to the newly created roles.

My current implementation technically works, but requires hardcoded locales, and results in many extra permissions being generated:

    for (const permission of permissions) {
      const roleHasThePermission = roleObject.permissions.some(perm => perm.action === permission.action && perm.subject === permission.subject)
      if (!roleHasThePermission) {
        await strapi.query('admin::permission').assignPermissions({ data: { 
          action: permission.action, 
          subject:permission.subject, 
          properties: {
            fields: permission.properties.fields,
            locales: ["en-US"]
          },
          conditions:permission.conditions, 
          role: roleObject.id, 
        } })
      }
    }

As far as I can tell from looking at the strapi core code, the assignPermissions method in the role service is built exactly for this. However whenever I try this and then build, I get Disk I/O errors, or the build hangs indefinitely.

const permissionsAttributes = permissions.map((perm) => {
    return {
      action:perm.action,
      subject:perm.subject,
      fields:perm.properties.fields,
      conditions:perm.conditions,
    }})

    strapi.service("admin::role").assignPermissions(roleObject.id, permissionsAttributes)
  });

This seems like a common use case, so if there is a simple solution out there I would appreciate the help.

Small typo, the working implementation uses create() not assignPermissions()

    for (const permission of permissions) {
      const roleHasThePermission = roleObject.permissions.some(perm => perm.action === permission.action && perm.subject === permission.subject)
      if (!roleHasThePermission) {
        await strapi.query('admin::permission').create({ data: { 
          action: permission.action, 
          subject:permission.subject, 
          properties: {
            fields: permission.properties.fields,
            locales: ["en-US"]
          },
          conditions:permission.conditions, 
          role: roleObject.id, 
        } })
      }
    }

Is it the solution for your question?