This example describes the Srbac plug-in usage of Yii. Share to everyone for your reference, specific as follows:
Yii RBAC, from the beginning to install the ARBC module expansion, to debug the analysis of its principles, intermittent also spent a lot of time. Of course, after you know it, you will find that Yii's ABRC is more convenient and allows you to easily achieve resource control access, very powerful. Now, just sort out the notes and share them. Although the Authmangner component implements RBAC, it does not implement visual editing management. At present there are Srbac and right two better extension modules, we use them very convenient visual management role (roles), Tasks (Task), Operations (operations).
role-based access Control (role-based access controls) is a simple and powerful centralized access control. The AuthManager component based on the Yii Framework realizes the hierarchical RBAC, which can help us to solve some resource control access problems in the development.
For these two expansion modules, in fact, the function is similar, but the interface is different. To see what style a person likes, choose that module test. As for installation and commissioning, you simply download them, which is described in detail. Below we analyze the principle of the implementation of the AuthManager component.
Authorization project is to determine whether a user is allowed to manipulate a particular resource, and to judge whether a user is a role that has access to the resource. Here we need to understand the relationship between authorized items, roles, tasks, and operations.
1. Authorized items can be divided into, roles, tasks, operations;
2. A role can be composed of several tasks;
3. A task may consist of several operations;
4. Operation is a license, not in the division.
Also mentioned here is the business rule problem, which is actually a section of PHP code that is executed when checking permissions.
Below we analyze the implementation of RBAC, need three tables: Authassignment, Authitem, authitemchild structure:
ItemName varchar (64) Role name, case-sensitive
UserID varchar (64) User ID, is the ID of the user table in your own project
BizRule text Business rules, a section of PHP code
An array of data text serialized to provide arguments to BizRule
The ItemName is the same in name varchar (authassignment)
Type integer type identification (0,1,2)
|
|--------0 indicates Operation operation
|--------1 indicates task tasks
|--------2 represents role
Description Text Related description
BizRule text Business rules, a section of PHP code
An array of data text serialized to provide arguments to BizRule
Parent varchar (64) Parents name, [role name, can also be a task];
Children varchar (64) Child object name. [Task name, can also be action];
Using the authentication Method Cwebuser::checkaccess (), the following is a demo code description:
if (Yii::app ()->user->checkaccess (What, $params)) {
//what ---role, or task, can also be operation,
// Params---is the parameter key-value that is passed into the business rule;
Here's a demonstration of how a user deletes an article:
$params =array (' uid ' => $id);
if (Yii::app ()->user->checkaccess (' delarticle ', $params)) {//
check whether the current user has delete Article permission
//and use business rules, Check the user ID equal to the author ID in the article
//verify, and then perform the delete operation
}
yii-srbac-permission Extension Module working principle
1, SET permission rules table: can be placed in module modules configuration file inside
Public Function init () {
//action permission table, the following fields must exist:
//itemname role name/ID,
//type authorized Project Type/1 (Task) or 2 (role),
// BizRule permission/Logical operation expression is false is a permission operation,
//data data/yii temporarily no use
yii::app ()->authmanager->itemtable = ' Authitem ';
Member group-permission corresponding table, the following fields must exist:
//child child role/id,
//parent parent role/id, this table can be cycled, multilevel inheritance
Yii::app ()->authmanager-> itemchildtable = ' uthitemchild ';
Member-member group corresponding table, the member group may directly for the operation name, must exist the following fields:
//itemname role name/ID,
//userid username/id,
//bizrule permissions/ The logical operation expression is false is the permission operation, the
//data data/yii temporarily does not use
yii::app ()->authmanager->assignmenttable = ' Zd_mem_glog ';
}
2, the implementation of the rules, the controller inherits the base class Sbasecontroller, originally controller
Class Productcontroller extends Sbasecontroller
{
...
}
Class Sbasecontroller extends Controller
{
...
}
3, Sbasecontroller inherits the base class controller, fills the Beforeaction, realizes the authority authentication.
protected function Beforeaction ($action) {//load module Separator $del = helper::findmodule (' Srbac ')->delimeter; $mod = $this->module!== null before getting the module name? $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 (initial capital) + method (first letter) Example: model-controlleraction if (sizeof ($CONTRARR) ==1) {$controller = Ucfirst ($contr
Oller); } $access = $mod. $controller.
Ucfirst ($this->action->id);
Verify that the access page address is in the Always Allow list, is returned with permission if (In_array ($access, $this->allowedaccess ()) {return true; //Verify that SRBAC has no installation, is not installed, the returned permission access if (!
Yii::app ()->getmodule (' Srbac ')->isinstalled ()) {return true;
//Verify that the SRBAC is open, is not on, the returned permission access if (Yii::app ()->getmodule (' Srbac ')->debug) {return true; }//permission validation if (! Yii::app ()->user->checkaccess ($access) | | YII:: App ()->user->isguest) {$this->onunauthorizedaccess ();
else {return true;
}
}
4, Cdbauthmanager read 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 read role 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 Read permission corresponding 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 authentication Authority
Public Function Executebizrule ($bizRule, $params, $data)
{return
$bizRule = = = ' | | $bizRule ===null | | ($this->showerrors eval_r ($bizRule)!=0: @eval_r ($bizRule)!=0);
}
Third, SRBAC test
Srbac Some of the configuration information that needs attention
Srbac the theme environment and how to integrate it into our specific project (you can put it in the modules directory and configure it in the configuration file).
In install we can choose whether to generate some test data, of course, if not generated, it does not matter, we can according to its rules to manually make some data configuration.
Before we introduce the configuration of the data, we need to have a little understanding of how the Srbac module works:
The Srbac module realizes the rights control through the mapping relationship between the roles--tasks--operations.
Users correspond to our customers
Roles corresponds to all role names required by our system
Operations corresponds to the name of all the specific actions we need to manage rights (for example, a specific action, we only allow a role to access)
In the SRBAC main interface we can see three icon, corresponding to the different operations.
Let's start by creating some of the data we need (corresponding to the first icon):
New operation: The naming of operation here needs to be noted and must be in controllernameactionname format. Controller, the name of the action, and the first letter of both must be capitalized.
Create a new task: a task can correspond to multiple operation, and we can name the task according to its function. For example, you can use news Management to represent a task for managing a story. Here the name does not have strict format requirements, as long as you do see the name of the idea can be.
Create a new roles: it's simple, it's typing the character we need.
OK, the data is new and complete. Next we came to the Assign page (corresponding to the second icon), the specific data to map settings.
According to the foregoing, assign operations to individual tasks, and then we assign tasks to specific role.
Finally, specify roles for user.
At this point, our authority configuration is basically over.
At this time, we can click on the third icon to view our specific user rights information when the correct.
Once the confirmation is correct, we will be able to verify our permissions.
However, there is a final step before that, and we want to make sure that the Srbac debug mode is turned off.
Because viewing the source code we will find that if the debug mode is turned on, our rights management will not work.
You can go to config/main.php for viewing:
' Modules ' => array ('
Srbac ' => Array (
' userclass ' => ' User ',
' userid ' => ' id ', ' username '
= > ' username ',
' Debug ' => false,//confirm this field
By this step, our permission module can be work. To check our configuration is normal, hehe
For more information on YII-related content, readers who are interested in this site can view the topics: Introduction to YII Framework and summary of common skills, "Summary of PHP Excellent development framework", "Smarty Template Introductory Course", "Introduction to PHP object-oriented programming", "PHP string" Summary of Usage , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"
I hope this article will help you with the PHP program design based on the YII framework.