Strapi插件路由默认权限

时间:2019-04-30 15:37:36

标签: strapi

我正在为Strapi构建具有多个路由的插件,例如:

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

安装插件后,任何经过身份验证的用户都应该能够使用新路由。我可以手动更改权限,以便路由正常工作,但这不是使用插件所需的工作流程。

如何设置插件路由的默认权限?

3 个答案:

答案 0 :(得分:1)

但是在Strapi中没有有关如何执行此操作的文档。

以下是如何使用permissions函数来获取,创建和更新权限strapi.plugins['users-permissions'].models.permission。那么如何处理。

您将必须在./config/function/bootstrap.js中编写代码。 每次服务器启动时都会执行此代码。

要创建权限,您必须找到要更新的角色(类型为authenticatedstrapi.plugins['users-permissions'].models.role.find

拥有角色的ID时,您将使用strapi.plugins['users-permissions'].models.permission.create

创建权限

要发送的对象参数:

  • 类型:将是您插件的名称
  • controller:根据您的情况,将是您的控制器importconfig的名称
  • action:您所用的函数preanalyzeimportfile的名称
  • 已启用:true
  • 角色:您要应用此政策的角色ID

答案 1 :(得分:0)

这是设置权限的方式。

// 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;
};

答案 2 :(得分:0)

对于Strapi版本3.0.0-beta.x及更高版本,

Create a global policy

isAuthenticated.js中创建一个名为./config/policies/的JavaScript文件

路径:./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!`);
};

在这里,我们正在验证会话是否打开。在这种情况下,我们调用next()方法,该方法将执行下一个策略或控制器的操作。否则,将返回401错误。

Use the policy in your routes

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