In Yii 2 RBAC, there is a new table called auth_rule. Can anyone explain its usage with a small example
create table [auth_rule]
(
[name] varchar(64) not null,
[data] text,
[created_at] integer,
[updated_at] integer,
primary key ([name])
);
The basic parts of yiis RBAC-cconcept stayed exactly the same. In both Yii1 and Yii2 you have the following tables:
auth_item
: holds the actual rights, groups, roles, etc.auth_item_child
: defines the graph / hierarchy of the itemsauth_assignement
: assigns an item to a userIn Yii2 you now have a fourth table:
auth_rule
: holds reusable rules to check if a right is actually grantedWhy is this?
The concept behind the rule was already there in Yii1...kind of at least. In Yii1 you had the possibility to define a "bizrule" in auth_item
and auth_assignement
. "bizrule" and "data" were columns in both those tables.
The contents of the columns were the following:
bizrule
: held php-code which had to return a boolean value. This code was executed during rights check with eval()
. That way you could control if a right was granted or not even though the user had the item assigned. Example: it makes no sense, but you could give a user a right only on even hours with this bizrule: return date('h') % 2 == 0
.data
: held params which could be passed to the bizrule while beeing executed. This data was then available in the scope of the bizrule.The above solution works perfectly, except that the code of a bizrule is not reusable. Therefore this functionality was extracted into its own table.
If you look at the migration-file creating the basic rbac-tables (yii\rbac\migrations\m140506_102106_rbac_init.php
) you can see that the item table now has a relation to the rule-table instead of hosting the code in one of its own columns.
There is however no relationship between auth_assignement
and auth_rule
. In Yii1 this allowed you to disable groups of rights at once. Since you can reuse a rule and attach it to all relevant items this is no longer necessary and was therefore removed.
If you look at the actual implementation of yii\rbac\DbManager
and yii\rbac\BaseManager
an example shouldn't be necessary. Interesting are the following mthods:
DbManager::addRule()
: serializes and persists a rule-instanceDbManager::getRule()
: here you can see how the rule is retrieved, unserialized and returned. This means the rule is saved in a serialized format within the data-column of auth_rule
.BaseManager::executeRule()
: the rule loaded above is executed via Rule::execute()
If you want to add a rule simply create an instance of yii\rbac\Rule
and call DbManager::addRule($rule)
with it as its param. This will serialize and save your rule making it reusable elsewhere. Awesome!
Voilà...should be pretty clear now. If you have some open questions or want more details just write a comment. Cheers and have a good one!