首页 > 活着 > YII RBAC

YII RBAC

YII非rbac通用权限,controller中加权限过滤器beforeaction

Java代码
1.public function purview($module, $control, $action) {
2. if (!Privilege::model()->checkPower($module, $control, $action)) {
3. throw new CHttpException(403, ‘您没有访问权限!’);
4. Yii::app()->end();
5. }
6.}
7.
8.// CGRIDVIEW buttonID ‘visible’ =>’$this->grid->controller->checkPower(“delete”)’,
9.public function checkPower($action, $contrl = null, $module = null) {
10. if ($contrl === null) {
11. $contrl = $this->getId();
12. }
13.
14. if ($module === null && $this->getModule()) {
15. $module = $this->getModule()->getId();
16. }
17.
18. return Privilege::model()->checkPower($module, $contrl, $action);
19.}
20.public function beforeAction($action) {
21. $contrl = $this->getId();
22. $actionId = $action->getId();
23. $route = $contrl . ‘/’ . $actionId;
24. if (!in_array($route, array(‘site/login’, ‘site/error’, ‘site/logout’)) && Yii::app()->user->id != 1) {
25. $module = null;
26. if ($action && $this->getModule()) {
27. $module = $this->getModule()->getId();
28. }
29. $this->purview($module, $contrl, $actionId);
30. }
31. return parent::beforeAction($action);
32.}
public function purview($module, $control, $action) {
if (!Privilege::model()->checkPower($module, $control, $action)) {
throw new CHttpException(403, ‘您没有访问权限!’);
Yii::app()->end();
}
}

// CGRIDVIEW buttonID ‘visible’ =>’$this->grid->controller->checkPower(“delete”)’,
public function checkPower($action, $contrl = null, $module = null) {
if ($contrl === null) {
$contrl = $this->getId();
}

if ($module === null && $this->getModule()) {
$module = $this->getModule()->getId();
}

return Privilege::model()->checkPower($module, $contrl, $action);
}
public function beforeAction($action) {
$contrl = $this->getId();
$actionId = $action->getId();
$route = $contrl . ‘/’ . $actionId;
if (!in_array($route, array(‘site/login’, ‘site/error’, ‘site/logout’)) && Yii::app()->user->id != 1) {
$module = null;
if ($action && $this->getModule()) {
$module = $this->getModule()->getId();
}
$this->purview($module, $contrl, $actionId);
}
return parent::beforeAction($action);
}在这里的visible表达式中设置调用$this->checkPower(‘操作名’);就可以隐藏没有权限访问的菜单了

RBAC0 定义了能构成一个RBAC控制系统的最小的元素集合
在RBAC之中,包含用户users(USERS)、角色roles(ROLES)、目标objects(OBS)、操作operations(OPS)、许可权permissions(PRMS)五个基本数据元素,权限被赋予角色,而不是用户,当一个角色被指定给一个用户时,此用户就拥有了该角色所包含的权限。会话sessions是用户与激活的角色集合之间的映射。RBAC0与传统访问控制的差别在于增加一层间接性带来了灵活性,RBAC1、RBAC2、RBAC3都是先后在RBAC0上的扩展。
RBAC1 引入角色间的继承关系
角色间的继承关系可分为一般继承关系和受限继承关系。一般继承关系仅要求角色继承关系是一个绝对偏序关系,允许角色间的多继承。而受限继承关系则进一步要求角色继承关系是一个树结构。
RBAC2 模型中添加了责任分离关系
RBAC2 的约束规定了权限被赋予角色时,或角色被赋予用户时,以及当用户在某一时刻激活一个角色时所应遵循的强制性规则。责任分离包括静态责任分离和动态责任分离。约束与用户-角色-权限关系一起决定了RBAC2模型中用户的访问许可。
RBAC3 包含了RBAC1和RBAC2

YII提供了2套权限访问系统,一套是简单的filter(过滤器)模式,另一套是复杂全面的RBAC模式,两者之间,前者先于后者。即访问的控制判断机制有个先后顺序:先进行访问控制过滤器的判断,再进行角色访问控制判断。而RBAC和默认的按照users的原理一样。通过指定”roles”来限定对应角色用户的可用action的权限。用”roles”替 换”users”即可,因为Yii的accessControl是支持roles的。通过这种方式,在Contoller内部,通过指定 accessRules就可以控制权限。在其他地方,比如控制一些view的显示的时候,可以用 Yii::app()->user->checkAccess(role)来进行权限判断。
RBAC本身也有特别之处。看官方的一段原话:
在Yii的RBAC的一个基本概念是authorization item(授权项目)。一个授权项目是一个做某事的许可(如创造新的博客发布,管理用户)。根据其粒度和targeted audience, 授权项目可分为operations(行动),tasks(任务)和 roles(角色)。角色包括任务,任务包括行动,行动是许可是个原子。 例如,我们就可以有一个administrator角色,包括post management和user management任务。user management 任务可能包括create user,update user和delete user行动。为了更灵活,Yii也可以允许角色包括其他角色和动作,任务包括其他任务,行动包括其他行动。
也就是说在Yii::app()->user->checkAccess(role)的时候,role可以是operations,tasks和roles。

rights,srbac可视化配置,自动安装表 http://www.yiiframework.com/extension/srbac/但是一定要弄懂Yii的内部 rbac 因为这扩展个都是建立在这个基础上的.

开始准备
Yii提供了强大的配置机制和很多现成的类库。在Yii中使用RBAC是很简单的,完全不需要再写RBAC代码。所以准备工作就是,打开编辑器,跟我来。 设置参数、建立数据库
在配置数组中,增加以下内容:

srbac

Java代码
1.’components’ => array(
2. ‘authManager’ => array(
3. ‘class’ => ‘srbac.components.SDbAuthManager’,
4. ‘connectionID’ => ‘db’, //使用的数据库组
5. ‘itemTable’ => ‘tbl_items’, // 授权项目表 (默认:authitem)
6. ‘assignmentTable’ => ‘tbl_assignments’, // 授权分配表 (默认:authassignment)
7. ‘itemChildTable’ => ‘tbl_itemchildren’, // 授权子项目表 (默认:authitemchild)
8. ),
9.),
‘components’ => array(
‘authManager’ => array(
‘class’ => ‘srbac.components.SDbAuthManager’,
‘connectionID’ => ‘db’, //使用的数据库组
‘itemTable’ => ‘tbl_items’, // 授权项目表 (默认:authitem)
‘assignmentTable’ => ‘tbl_assignments’, // 授权分配表 (默认:authassignment)
‘itemChildTable’ => ‘tbl_itemchildren’, // 授权子项目表 (默认:authitemchild)
),
),注意这里,’class’=>’srbac.components.SDbAuthManager’, 手册上写的错了

那这三个数据表怎么建立呢?很简单,去看framework/web/auth/schema.sql。注意要和你的自定义的表名称对应起来。然后在数据库中运行这个SQL文件中的语句。

修改对应的配置

Java代码
1.’modules’ => array(
2. ‘srbac’ => array(
3. ‘userclass’ => ‘Member’, //default: User
4. ‘userid’ => ‘mid’, //default: userid
5. ‘username’ => ‘username’, //default:username
6.****
‘modules’ => array(
‘srbac’ => array(
‘userclass’ => ‘Member’, //default: User
‘userid’ => ‘mid’, //default: userid
‘username’ => ‘username’, //default:username
****index.php?r=srbac,安装成功可以删除modules\srbac\views\authitem\install文件夹也可以重命名。然后找到protected\modules\srbac\controllers\AuthitemController.php注释掉beforeAction方法中代码。

Java代码
1.if (!$this->module->isInstalled() && $action->id != “install”) {
2. $this->redirect(array(“install”));
3. return false;
4.}
if (!$this->module->isInstalled() && $action->id != “install”) {
$this->redirect(array(“install”));
return false;
} rights有4个表在data下

Java代码
1.’import’ => array(
2. // rights
3. ‘application.modules.rights.*’,
4. ‘application.modules.rights.models.*’,
5. ‘application.modules.rights.components.*’, // Correct paths if necessary.
6.),
7.
8.’modules’ => array(
9. ‘rights’ => array(
10. //’debug’ => true,
11. ‘install’ => true,
12. //’enableBizRuleData’ => true,
13. ),
14.),
15.’components’ => array(
16. ‘authManager’ => array(
17. ‘class’ => ‘RDbAuthManager’,
18. ‘connectionID’ => ‘db’,
19. ‘itemTable’ => ‘r_auth_item’,
20. ‘itemChildTable’ => ‘r_auth_item_child’,
21. ‘assignmentTable’ => ‘r_auth_assignment’,
22. ‘rightsTable’ => ‘r_rights’,
23. ),
24. ‘user’ => array(
25. ‘class’ => ‘RWebUser’,
26. ),
27.)
‘import’ => array(
// rights
‘application.modules.rights.*’,
‘application.modules.rights.models.*’,
‘application.modules.rights.components.*’, // Correct paths if necessary.
),

‘modules’ => array(
‘rights’ => array(
//’debug’ => true,
‘install’ => true,
//’enableBizRuleData’ => true,
),
),
‘components’ => array(
‘authManager’ => array(
‘class’ => ‘RDbAuthManager’,
‘connectionID’ => ‘db’,
‘itemTable’ => ‘r_auth_item’,
‘itemChildTable’ => ‘r_auth_item_child’,
‘assignmentTable’ => ‘r_auth_assignment’,
‘rightsTable’ => ‘r_rights’,
),
‘user’ => array(
‘class’ => ‘RWebUser’,
),
)rights

Java代码
1.class Controller extends RController {
2. public function filters() {
3. return array(
4. ‘rights’,
5. );
6. }
7.}
class Controller extends RController {
public function filters() {
return array(
‘rights’,
);
}
}进行赋权

我们建立了RBAC权限管理,就需要进行对权限的WEB管理。这些就需要你自己写代码了。
根据不同种类的项目调用下列方法之一定义授权项目 :

* CAuthManager::createRole
* CAuthManager::createTask
* CAuthManager::createOperation

一旦我们拥有一套授权项目,我们可以调用以下方法建立授权项目关系:
* CAuthManager::addItemChild
* CAuthManager::removeItemChild
* CAuthItem::addChild
* CAuthItem::removeChild

最后,我们调用下列方法来分配角色项目给各个用户:
* CAuthManager::assign
* CAuthManager::revoke

权限数据的添加 项目调用定义授权项目后会在table中插入相应的数据

2.

Java代码
1. 2.class RbacController extends CController{
3./** @method 动作过滤器 */
4.public function filters() {
5. return array(
6. 'checkLogin - login,logout', //-号是除了login,logou之外的动作全部要执行checkLogin 这个验证
7. 'checkRole - login,logout,index', //如果是+号是,只执行login,logou的动作才会执行checkLogin 这个验证
8. 'checkModifyPwd - login,logout,modifypwd'
9. );
10.}
11.public function accessRules()
12.{
13. return array(
14. array(
15. 'allow',
16. 'actions' => array(‘deletePost’),
17. ‘roles’ => array(‘deletePost’),
18. ),
19. array(
20. ‘allow’,
21. ‘actions’ => array(‘init’, ‘test’),
22. ),
23. array(‘deny’),
24. );
25.}
26.public function actionInit()
27.{
28. $auth=Yii::app()->authManager;
29. $auth->createOperation(‘createPost’,’create a post’);
30. $auth->createOperation(‘readPost’,’read a post’);
31. $auth->createOperation(‘updatePost’,’update a post’);
32. $auth->createOperation(‘deletePost’,’delete a post’);
33. $bizRule=’return Yii::app()->user->id==$params[“post”]->authID;';
34. $task=$auth->createTask(‘updateOwnPost’,’update a post by author himself’,$bizRule);
35. $task->addChild(‘updatePost’);
36. $role=$auth->createRole(‘reader’);
37. $role->addChild(‘readPost’);
38. $role=$auth->createRole(‘author’);
39. $role->addChild(‘reader’);
40. $role->addChild(‘createPost’);
41. $role->addChild(‘updateOwnPost’);
42. $role=$auth->createRole(‘editor’);
43. $role->addChild(‘reader’);
44. $role->addChild(‘updatePost’);
45. $role=$auth->createRole(‘admin’);
46. $role->addChild(‘editor’);
47. $role->addChild(‘author’);
48. $role->addChild(‘deletePost’);
49. $auth->assign(‘reader’,’readerA’);
50. $auth->assign(‘author’,’authorB’);
51. $auth->assign(‘editor’,’editorC’);
52. $auth->assign(‘admin’,’adminD’);
53. echo “Done.”;
54.}
55.public function actionDeletePost()
56.{
57. echo “Post deleted.”;
58.}
59.public function actionTest()
60.{
61. $post = new stdClass();
62. $post->authID = ‘authorB';
63. echo “Current permissions:
“;
64. echo “

    “;
    65. echo “
  • Create post: “.Yii::app()->user->checkAccess(‘createPost’).”
  • “;
    66. echo “

  • Read post: “.Yii::app()->user->checkAccess(‘readPost’).”
  • “;
    67. echo “

  • Update post: “.Yii::app()->user->checkAccess(‘updatePost’, array(‘post’ => $post)).”
  • “;
    68. echo “

  • Delete post: “.Yii::app()->user->checkAccess(‘deletePost’).”
  • “;
    69. echo “

“;
70.}
71.
72.}
class RbacController extends CController{
/** @method 动作过滤器 */
public function filters() {
return array(
'checkLogin - login,logout', //-号是除了login,logou之外的动作全部要执行checkLogin 这个验证
'checkRole - login,logout,index', //如果是+号是,只执行login,logou的动作才会执行checkLogin 这个验证
'checkModifyPwd - login,logout,modifypwd'
);
}
public function accessRules()
{
return array(
array(
'allow',
'actions' => array(‘deletePost’),
‘roles’ => array(‘deletePost’),
),
array(
‘allow’,
‘actions’ => array(‘init’, ‘test’),
),
array(‘deny’),
);
}
public function actionInit()
{
$auth=Yii::app()->authManager;
$auth->createOperation(‘createPost’,’create a post’);
$auth->createOperation(‘readPost’,’read a post’);
$auth->createOperation(‘updatePost’,’update a post’);
$auth->createOperation(‘deletePost’,’delete a post’);
$bizRule=’return Yii::app()->user->id==$params[“post”]->authID;';
$task=$auth->createTask(‘updateOwnPost’,’update a post by author himself’,$bizRule);
$task->addChild(‘updatePost’);
$role=$auth->createRole(‘reader’);
$role->addChild(‘readPost’);
$role=$auth->createRole(‘author’);
$role->addChild(‘reader’);
$role->addChild(‘createPost’);
$role->addChild(‘updateOwnPost’);
$role=$auth->createRole(‘editor’);
$role->addChild(‘reader’);
$role->addChild(‘updatePost’);
$role=$auth->createRole(‘admin’);
$role->addChild(‘editor’);
$role->addChild(‘author’);
$role->addChild(‘deletePost’);
$auth->assign(‘reader’,’readerA’);
$auth->assign(‘author’,’authorB’);
$auth->assign(‘editor’,’editorC’);
$auth->assign(‘admin’,’adminD’);
echo “Done.”;
}
public function actionDeletePost()
{
echo “Post deleted.”;
}
public function actionTest()
{
$post = new stdClass();
$post->authID = ‘authorB';
echo “Current permissions:
“;
echo “

    “;
    echo “
  • Create post: “.Yii::app()->user->checkAccess(‘createPost’).”
  • “;
    echo “

  • Read post: “.Yii::app()->user->checkAccess(‘readPost’).”
  • “;
    echo “

  • Update post: “.Yii::app()->user->checkAccess(‘updatePost’, array(‘post’ => $post)).”
  • “;
    echo “

  • Delete post: “.Yii::app()->user->checkAccess(‘deletePost’).”
  • “;
    echo “

“;
}

} UserIdentity.php

Java代码
1.$users=array(
2. // username => password
3. ‘demo’=>’demo’,
4. ‘admin’=>’admin’,
5. ‘readerA’=>’123′,
6. ‘authorB’=>’123′,
7. ‘editorC’=>’123′,
8. ‘adminD’=>’123′,
9.);
$users=array(
// username => password
‘demo’=>’demo’,
‘admin’=>’admin’,
‘readerA’=>’123′,
‘authorB’=>’123′,
‘editorC’=>’123′,
‘adminD’=>’123′,
); 运行?r=Rbac/init插入rbac数据,在用readerA,authorB,editorC…登录后访问?r=Rbac/test查看对应的权限检查页面

权限检查
假设你在你的管理界面进行了赋权,那么可以在程序里面进行权限检查:

Java代码
1.$project = Project::model()->findByPk($row1[‘project_id’]);
2.$auth = Yii::app()->authManager;
3.$bizRule = ‘return isset($params[“project”]) &&$params[“project”]->isUserInRole(“member”);';
4.$auth->assign(‘member’, $row1[‘user_id’], $bizRule);
5.$params = array(‘project’ => $project);
6.if (Yii::app()->user->checkAccess(‘updateIssue’, $params)) {
7. // 这里可以显示表单等操作
8.} else {
9. // 检查没有通过的可以跳转或者显示警告
10.}
$project = Project::model()->findByPk($row1[‘project_id’]);
$auth = Yii::app()->authManager;
$bizRule = ‘return isset($params[“project”]) &&$params[“project”]->isUserInRole(“member”);';
$auth->assign(‘member’, $row1[‘user_id’], $bizRule);
$params = array(‘project’ => $project);
if (Yii::app()->user->checkAccess(‘updateIssue’, $params)) {
// 这里可以显示表单等操作
} else {
// 检查没有通过的可以跳转或者显示警告
}上面的代码就检查了用户是否可以执行“updateIssue”,这updateIssue可能是一个任务,也可以是一个行动。

控制action方式
Java代码
1.public function filters()
2.{
3. return array(
4. ‘accessControl’, // perform access control for CRUD operations
5. ‘postOnly + delete’, //actiondelete方法只能用POST方式提交。
6. ‘ajaxOnly tree’,//actionTree方法只能用ajax方式提交。
7. );
8.}
public function filters()
{
return array(
‘accessControl’, // perform access control for CRUD operations
‘postOnly + delete’, //actiondelete方法只能用POST方式提交。
‘ajaxOnly tree’,//actionTree方法只能用ajax方式提交。
);
} dxxx

YII非rbac通用权限,controller中加权限过滤器beforeaction Java代码 1.pub […]

  1. 还没有评论
评论提交中, 请稍候...

留言

(Spamcheck Enabled)

Trackbacks & Pingbacks ( 0 )
  1. 还没有 trackbacks