Yisrbac and yiisrbac
This example describes the usage of the Yii Srbac plug-in. We will share this with you for your reference. The details are as follows:
Rbac of Yii, from the installation of arbc module extension, to the debugging and analysis of its principles, also took a lot of time. After learning about it, you will find that the abrc of yii is much more convenient, which makes resource control and access very powerful. Now let's sort out the study notes and share them with you. Although the authMangner component implements rbac, it does not implement visual editing management. Currently, there are two good extension modules: Srbac and Right. We use them to easily visualize roles, tasks, and operations ).
Role-Based Access Control is a simple and powerful centralized Access Control. The authManager component based on Yii Framework implements a hierarchical RBAC, which helps us solve some resource access control problems during development.
The two extension modules have similar functions, but the interface is different. Choose the module to test if you like it. As for installation and debugging, you only need to download them for details. Next we will analyze the implementation principles of the authManager component.
An authorized project is used to determine whether a user is allowed to operate on a specific resource. It is determined by checking whether the user is authorized to access the resource. Here we need to understand the relationship between authorized projects, roles, tasks, and operations.
1. Authorized projects can be divided into roles, tasks, and operations;
2. A role can be composed of several tasks;
3. A task may consist of several operations;
4. The operation is a license and cannot be divided.
It is also mentioned that the business rule is actually a piece of php code that will be executed when checking permissions.
Next, we will analyze the structure of three tables in rbac implementation: authassignment, authitem, and authitemchild:
Itemname varchar (64) role name, case sensitive
Userid varchar (64) User id, which is the id of the User table used in your project
Bizrule text business rule, a piece of php code
Serialized array of data text, used to provide parameters for bizrule
Name varchar (64) The itemname in authassignment is the same
Type integer type identifier (0, 1, 2)
|
| -------- 0 indicates the Operation
| -------- 1 indicates the Task
| -------- 2 indicates the Role
Description text description
Bizrule text business rule, a piece of php code
Serialized array of data text, used to provide parameters for bizrule
Parent varchar (64) parent name, [role name, or task];
Children varchar (64) Sub-Object Name. [Task Name or operation];
Use the verification method CWebUser: checkAccess (). The demo code is described below:
If (Yii: app ()-> user-> checkAccess (what, $ params) {// what --- role, or task, or operation, // params --- is the key-value parameter passed into the business rule ;}
The following describes how to delete an article:
$ Params = array ('uid' => $ id); if (Yii: app ()-> user-> checkAccess ('delarticle', $ params )) {// check whether the current user has the permission to delete an article. // use the business rules and check whether the user id is equal to the author id in the article. // if the user id is verified, perform the delete operation}
How the Yii-srbac-Permission extension module works
1. Set the permission rule table: It can be placed in the module configuration file.
Public function init () {// operation permission table, which must have the following fields: // itemname role name/ID, // type authorization project type/1 (task) or 2 (role), // bizrule permission/If the logic expression is false, the operation is permitted. // data/YII has not used Yii: app () -> authManager-> itemTable = 'authitem'; // member group-Permission table. The following fields must exist: // child subrole/ID, // parent role/ID. This table can be cyclically executed and can inherit Yii: app ()-> authManager-> itemChildTable = 'uthitemchild 'in multiple levels '; // member-the table corresponding to the member group. The member group can be the operation name directly. The following fields must exist: // itemname role name/ID, // userid username/ID, // bizrule permission/If the logical expression is false, the operation is permitted. // data/YII is not currently using Yii: app () -> authManager-> assignmentTable = 'zd _ mem_glog ';}
2. Implementation Rules. The Controller belongs to the SBaseController class and is originally a Controller.
class ProductController extends SBaseController{ ........}class SBaseController extends Controller{ ........}
3. SBaseController inherits the base class Controller and adds beforeAction to the front to implement permission verification.
Protected function beforeAction ($ action) {// loading module separator $ del = Helper: findModule ('srbac ')-> delimeter; // obtain the previous module name $ mod = $ this-> module! = Null? $ This-> module-> id. $ del: ""; $ contrArr = explode ("/", $ this-> id); $ contrArr [sizeof ($ contrArr) -1] = ucfirst ($ contrArr [sizeof ($ contrArr)-1]); $ controller = implode (". ", $ contrArr); $ controller = str_replace ("/",". ", $ this-> id); // generate static page module + separator + controller (uppercase letter) + method (uppercase letter) Example: model-ControllerAction if (sizeof ($ contrArr) = 1) {$ controller = ucfirst ($ controller);} $ access = $ mod. $ controller. ucfirst ($ This-> action-> id); // verify whether the access page address is always in the allowed list. if (in_array ($ access, $ this-> allowedAccess () {return true;} // verify whether SRBAC is installed. if (! Yii: app ()-> getModule ('srbac ')-> isInstalled () {return true;} // check whether srbac is enabled and is not enabled, returned permission access if (Yii: app ()-> getModule ('srbac ')-> debug) {return true;} // permission verification if (! Yii: app ()-> user-> checkAccess ($ access) | Yii: app ()-> user-> isGuest) {$ this-> onUnauthorizedAccess () ;}else {return true ;}}
4. CDbAuthManager reads the current user role
public function getAuthAssignments($userId){ $rows=$this->db->createCommand() ->select() ->from($this->assignmentTable) ->where('userid=:userid', array(':userid'=>$userId)) ->queryAll(); $assignments=array(); foreach($rows as $row) { if(($data=@unserialize($row['data']))===false) $data=null; $assignments[$row['itemname']]=new CAuthAssignment($this,$row['itemname'],$row['userid'],$row['bizrule'],$data); } return $assignments;}
5. CDbAuthManager reads the role's corresponding Permissions
public function getAuthItem($name){ $row=$this->db->createCommand() ->select() ->from($this->itemTable) ->where('name=:name', array(':name'=>$name)) ->queryRow(); if($row!==false) { if(($data=@unserialize($row['data']))===false) $data=null; return new CAuthItem($this,$row['name'],$row['type'],$row['description'],$row['bizrule'],$data); } else return null;}
6. CDbAuthManager operation
protected function checkAccessRecursive($itemName,$userId,$params,$assignments){ if(($item=$this->getAuthItem($itemName))===null) return false; Yii::trace('Checking permission "'.$item->getName().'"','system.web.auth.CDbAuthManager'); if(!isset($params['userId'])) $params['userId'] = $userId; if($this->executeBizRule($item->getBizRule(),$params,$item->getData())) { if(in_array($itemName,$this->defaultRoles)) return true; if(isset($assignments[$itemName])) { $assignment=$assignments[$itemName]; if($this->executeBizRule($assignment->getBizRule(),$params,$assignment->getData())) return true; } $parents=$this->db->createCommand() ->select('parent') ->from($this->itemChildTable) ->where('child=:name', array(':name'=>$itemName)) ->queryColumn(); foreach($parents as $parent) { if($this->checkAccessRecursive($parent,$userId,$params,$assignments)) return true; } } return false;}
7. CAuthManager verifies Permissions
public function executeBizRule($bizRule,$params,$data){ return $bizRule==='' || $bizRule===null || ($this->showErrors ? eval_r($bizRule)!=0 : @eval_r($bizRule)!=0);}
Iii. SRBAC Testing
Some configuration information in SRBAC
The setup of the SRBAC theme environment and how to integrate it into our specific project (you can put it under the modules directory and then perform some configuration in the configuration file) are described above.
During install, we can choose whether to generate some test data. Of course, it doesn't matter if it is not generated. We can manually configure some data according to its rules.
Before introducing the Data configuration, we need to understand the working principle of a new SRBAC module:
The SRBAC module implements permission control through the ing between roles -- tasks -- operations.
Users corresponds to our users
Roles corresponds to all role names required by our system
Operations correspond to the names of all specific operations that require permission management (for example, a specific action, we only allow a specific role to access)
On the main interface of SRBAC, we can see three icons corresponding to different operations.
We will first create some data information (corresponding to the first icon) We need ):
Create a specific operation: The operation name must be in the ControllernameActionname format. The name combination of controller and action, and the first letter of both must be capitalized.
Create a specific task: a task can correspond to multiple operations. We can name the task according to the corresponding functions. For example, News Management can be used to represent News Management tasks. There are no strict format requirements for naming, as long as you know what you mean.
Create a specific roles: This is very simple, just enter the role we need.
OK. The data is created. Next we will go to the assign page (corresponding to the second icon) and set the ing of the specific data.
As mentioned above, operations are assigned to each task, and then tasks are assigned to the specific role.
Finally, specify the roles for the user.
In this step, the permission configuration is complete.
In this case, we can click the third icon to view the permission information of our specific user.
After confirmation, we can verify our permissions.
However, there is still a last step before that. We need to confirm that the debug mode of SRBAC has been disabled.
If the debug mode is enabled, permission management does not work.
You can view it in config/main. php:
'modules' => array( 'srbac' => array( 'userclass' => 'User', 'userid' => 'id', 'username' => 'username', 'debug' => false,//confirm this field
In this step, our permission module can work. Check whether our configuration is normal.