2

I am building a plugin for Strapi with several routes, for example:

    {
      "method": "GET",
      "path": "/preAnalyzeImportFile",
      "handler": "ImportConfig.preAnalyzeImportFile",
      "config": {
        "policies": ["global.isAuthenticated"]
      }
    }

When the plugin is installed, any authenticated user should be able to use the new routes. I can change the permissions manually so that the routes work, but that should not be a required workflow to use the plugin.

How do I set default permissions for plugin routes?

Joe Beuckman
  • 2,264
  • 2
  • 24
  • 63

4 Answers4

2

There is no documentation about how to do it in Strapi but.

Here is how to use permissions function to get, create, update permissions strapi.plugins['users-permissions'].models.permission. So how to deal with.

You will have to write your code in the ./config/function/bootstrap.js. This code is executed every time your server start.

To create your permission you will have to find the role you want to update (with the type authenticated) strapi.plugins['users-permissions'].models.role.find.

When you have the id of the role you will create a permission with strapi.plugins['users-permissions'].models.permission.create

Object params to send:

  • type: will be the name of your plugin
  • controller: will be the name of your controller importconfig in your case
  • action: the name of the function preanalyzeimportfile in your case
  • enabled: true
  • role: the role id you want to apply this policy
Jim LAURIE
  • 3,859
  • 1
  • 11
  • 14
  • Is there a way to run once when the plugin is installed? – Joe Beuckman May 07 '19 at 08:07
  • You can't use a `post-install` script because you will not have access to the `strapi` variable. You will have to check it on every start. But a solution can be to add a config file in your plugin and to set a `init` attribute to false by default, and update it to true when your create your permissions for the first time. – Jim LAURIE May 07 '19 at 08:26
  • Great - I will do that. I didn't see an example of using custom config from plugins - can you point me to docs or a plugin that uses it's own config (some other config than routes/queries/functions/policies)? – Joe Beuckman May 07 '19 at 08:30
  • Here for the GraphQL plugin https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-graphql/config/settings.json – Jim LAURIE May 07 '19 at 11:35
  • Is there any reason not to use `strapi.store` to flag whether init has run? – Joe Beuckman May 07 '19 at 20:24
  • #2: I am getting "strapi.plugins.users-permissions.models.role.find is not a function". I'm always confused about whether models.etc. is something from Strapi or a mongoose or bookshelf model directly or what. – Joe Beuckman May 07 '19 at 21:13
  • 1
    #3 This seems okay: `await strapi .query('role', 'users-permissions') .findOne({ type: 'authenticated' })` – Joe Beuckman May 07 '19 at 21:33
  • 1
    Ho yes you can use the `core store` if you want to store if the setup of your plugin is done or not. You will find documentation of the usage of this API here https://strapi.io/documentation/3.x.x/configurations/configurations.html#database-configuration – Jim LAURIE May 09 '19 at 09:28
  • I'm getting strapi.plugins.users-permissions.models.permission.create is not a function. Does this method still work? – Quinn Keaveney May 05 '20 at 21:12
0

This is how you set permissions.

// In your bootstrap.js file
'use strict';
module.exports = async () => {

    const authenticated = await strapi.query('role', 'users-permissions').findOne({ type: 'authenticated' });
    authenticated.permissions.forEach(permission => {

        if (permission.type === 'application'){ // Whatever permissions you want to change
            let newPermission = permission;
            newPermission.enabled = true; // Editing permission as needed

            strapi.query('permission', 'users-permissions').update( { id: newPermission.id }, newPermission ); // Updating Strapi with the permission
        }
    });
    return;
};
Quinn Keaveney
  • 1,248
  • 1
  • 17
  • 39
0

For Strapi version 3.0.0-beta.x & later,

Create a global policy

Create a JavaScript file named isAuthenticated.js in ./config/policies/

Path: ./config/policies/isAuthenticated.js

module.exports = async (ctx, next) => {
  if (ctx.state.user) {
    // Go to next policy or will reach the controller's action.
    return await next();
}

  ctx.unauthorized(`You're not logged in!`);
};

Here, we are verifying that a session is open. If it is the case, we call the next() method that will execute the next policy or controller's action. Otherwise, a 401 error is returned.

Use the policy in your routes

 {
   "method": "GET",
   "path": "/preAnalyzeImportFile",
   "handler": "ImportConfig.preAnalyzeImportFile",
   "config": {
     "policies": ["global::isAuthenticated"]
  }
}
Anubhav Das
  • 940
  • 1
  • 11
  • 16
0

Here's how to set plugins permissions programatically in Strapi v4:

  const wantedPermission =await strapi
   .query("plugin::users-permissions.permission")
   .findOne({where: {action: "api::testssd.testssd.find"}});

  const publicRole = await strapi
  .query('plugin::users-permissions.role')
  .findOne({where: {type: "public"}, populate: ['users', 'permissions']});

  //add the permission to the public role in the db if not already present
  if (!publicRole.permissions.some(permission => permission.action == "api::testssd.testssd.find")) {
    publicRole.permissions.push(wantedPermission);
    await strapi.query('plugin::users-permissions.role').update({
       where: {id: publicRole.id},
      data: {permissions: publicRole.permissions},
    });
  }
Ana
  • 312
  • 2
  • 9