How to create programmatically new roles and add restrictions in strapi required help

System Information
  • Strapi Version:4.16.2
  • Operating System: windows 11
  • Database: postgres
  • Node Version: 18.17.0
  • NPM Version: 9.6.7
  • Yarn Version: 1.22.21

the strapi provides and option to create a new roles and restric user to access certain api function like create read update delete how to manage this functionality programmatically via api

@hashirnouman First You need to understand how Strapi users-permissions plugin works
If you look into you db you will see following tables

  1. up_permissions
  2. up_permissions_role_links
  3. up_roles

roles and permissions of user is managed using these tables and you can create custom api and perfrom curd on above tables to add new roles programmatically
you can acess table like

        strapi.db.connection
          .table('up_roles')

strapi use KNEX ORM under the table so you can read KNEX Documentation for better understanding

Any snippet for it?

@LuisAlaguna @hashirnouman here is snippet to create role using strapi Query Engine’s API

await strapi.db
        .query('plugin::users-permissions.role')
        .create({
          data: {
            name: 'Teacher',
            description: 'Teacher can upload grades',
            type: 'authenticated'
          }
        });

similarly below example create a permission for find course api

await strapi.db
        .query('plugin::users-permissions.permission')
        .create({
          data: {
            action: 'api::course.course.find',
          }
        });

and if you want to assign a new role permission using nested like

await strapi.db
        .query('plugin::users-permissions.role')
        .create({
          data: {
            name: 'Teacher',
            description: 'Default message',
            type: 'authenticated',
        // permission id of find course api
            permissions: [11]
          }
        });
1 Like