Yii 2.0 RBAC 权限管理测试
Yii 2.0 RBAC 权限管理测试:
1. 执行命令创建表: ./yii migrate --migrationPath=@yii/rbac/migrations/
components 添加 authManager 配置:
'authManager' => [ 'class' => 'yii\rbac\DbManager', 'itemTable' => 'auth_item', 'assignmentTable' => 'auth_assignment', 'itemChildTable' => 'auth_item_child', ],
2. 创建rule 方法
<?php namespace common\components; use yii\rbac\Rule;//从系统自带规则继承 /** * Checks if authorID matches user passed via params * 检查authorID是否与已经通过参数的用户匹配 */ class AuthorRule extends Rule { public $name = 'isAuthor'; /** * @param string|integer $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 boolean a value indicating whether the rule permits the role or permission it is associated with. */ public function execute($user, $item, $params)//实现rule抽象类里的extends方法 { return isset($params['userid']) ? $params['userid'] == $user : false;//把传送进来的用户id,与当前登录的用户id对比。 } }
3. 测试:
$auth = Yii::$app->authManager; //创建agent权限 $rule = new \common\components\AuthorRule;//使用创建的类文件创建对象 $auth->add($rule);//执行后去看看表是不是多了一条记录 $agentPermission = $auth->createPermission('agent'); $agentPermission->ruleName = 'isAuthor'; $agentPermission->description = 'create agent operate permission.'; $agentPermission->data = $rule; $auth->add($agentPermission); //创建admin角色 $adminRole = $auth->createRole('admin'); $adminRole->ruleName = 'isAuthor'; $adminRole->description = '创建管理员角色'; $auth->add($adminRole); //将权限赋予角色 $auth->addChild($adminRole, $agentPermission); //将角色赋予用户 $userId = 25; $auth->assign($adminRole, $userId); # 权限检查 // $controller = Yii::$app->controller->id; // $action = Yii::$app->controller->action->id; // $permission_name = $controller . '/' . $action; $permission_name = $action->controller->module->requestedRoute;//记录我们访问的规则名称 if (!\Yii::$app->user->can('agent',['userid' => '25'])) { throw new \yii\web\UnauthorizedHttpException('对不起,您现在还没获此操作的权限'); } exit;
问题:
数据级别的权限问题, 如当前用户查看列表时, 只能看到的自己有权限的数据?