首页 > 解决方案 > Yii2 - RBAC 规则允许/查看自己的数据

问题描述

我已经yii2mod/yii2-rbac从这个 url 安装了 - https://github.com/yii2mod/yii2-rbac in yii2-basic。

除了使用/允许所有者数据外,一切正常。

从这个链接:https ://www.yiiframework.com/doc/guide/2.0/en/security-authorization 我在根目录rbac和文件AuthorRule.php和代码中创建了一个文件夹:

namespace app\rbac;

use yii\rbac\Rule;

//use app\models\Post;

/**
 * Checks if authorID matches user passed via params
 */
class AuthorRule extends Rule
{
    /**
     * @var string
     */
    public $name = 'isAuthor';

    /**
     * @param string|int $user the user ID.
     * @param Item $item the role or permission that this rule is associated with
     * @param array $params parameters passed to ManagerInterface::checkAccess().
     * @return bool a value indicating whether the rule permits the role or permission it is associated with.
     */
    public function execute($user, $item, $params)
    {
        return isset($params['post']) ? $params['post']->createdBy == $user : false;
    }
}

但是当我尝试在权限中添加规则时(AuthorRule或者isAuthor在我创建 updateOwnRecord 的权限下,我收到错误,规则不存在。

我在这里缺少什么?

标签: phpyii2yii2-basic-appyii2-rbac

解决方案


但是当我尝试在权限中添加规则时(AuthorRule 或 isAuthor 在我创建 updateOwnRecord 的权限下,我收到错误,规则不存在

由于没有相关代码,不确定您在哪里得到您提到的错误,但是查看您的详细信息我认为您没有正确理解该过程。

  • 在. updatePost_auth_item
  • AuthorRule类的序列化实例添加到auth_rule表中。
  • 创建新权限updateOwnPost并指定规则名称,即isAuthor.
  • 将权限updatePost作为子项添加到UpdateOwnPostauth_item_child中。
    • isAuthor是您将提供给updateOwnPost权限rule_name列的规则的名称。
  • 添加updatePost作为role您要为其使用规则的子项,user或者您为标准用户角色创建的任何其他人。

请参阅下面的代码,您现在可以通过任何临时操作运行一次,我们将在后面的答案中讨论它的位置。

$auth = Yii::$app->authManager;
$updatePost = $auth->getPermission('updatePost');

//change it to whichever role you want to assign it like `user` `admin` or any other role
$role = $auth->getRole('user');

// add the rule
$rule = new \app\rbac\AuthorRule;
$auth->add($rule);

// add the "updateOwnPost" permission and associate the rule with it.
$updateOwnPost = $auth->createPermission('updateOwnPost');
$updateOwnPost->description = 'Update own post';
$updateOwnPost->ruleName = $rule->name;
$auth->add($updateOwnPost);

// "updateOwnPost" will be used from "updatePost"
$auth->addChild($updateOwnPost, $updatePost);

// allow "author" to update their own posts
$auth->addChild($role, $updateOwnPost);

现在,如果一切顺利,您可以通过运行上面的代码来添加规则

请记住,您需要检查updatePost规则Yii::$app->user->can() 而不是updateOwnPost检查规则并将Post模型实例作为第二个参数传递

像这样

if (\Yii::$app->user->can('updatePost', ['post' => $post])) {
    // update post
}

关于当前应用中的代码放置

如果您想拥有一个单独的界面,您可以在其中添加 create all 表单,那么您可以按照现有的dektrium-rbac代码提供完整的 crud,您可以根据自己的要求使用这些代码。

参考见下文

注意:如果您有很多控制器,并且您希望将此规则与控制器内的每个更新操作相关联(假设所有关联的模型都具有该created_by字段),那么您可以console\Controller通过控制台运行此类进程,以便每个newcontroller/update可以与在循环内重复上述过程的规则相关联。有关基本应用程序中的控制台控制器用法,请参见此处


推荐阅读