but when I try to add the rule in permission(either AuthorRule or
isAuthor under permission I created updateOwnRecord, I am getting the
error, the rule doesn't exist
Not sure where you are getting the error you mentioned as there is no relevant code, but looking at your details i recon you havent understood the process correctly.
- Create a permission
updatePost
in the auth_item
.
- Add
AuthorRule
class's serialized instance to auth_rule
table.
- Create a new permission
updateOwnPost
and specify the rule name i.e isAuthor
.
- Add the permission
updatePost
as a child to UpdateOwnPost
in the auth_item_child
table.
- the
isAuthor
will be the name of the rule that you will supply to the updateOwnPost
permission's rule_name
column.
- Add the
updatePost
as a child of the role
you want to use the rule for, like user
or anyother you have created for the standard user role.
See the below code you can run it once via any temporary action for now, we will discuss it's place later in the answer below.
$auth = Yii::$app->authManager;
$updatePost = $auth->getPermission('updatePost');
//change it to whichever role you want to assign it like `user` `admin` or any other role
$role = $auth->getRole('user');
// add the rule
$rule = new \app\rbac\AuthorRule;
$auth->add($rule);
// add the "updateOwnPost" permission and associate the rule with it.
$updateOwnPost = $auth->createPermission('updateOwnPost');
$updateOwnPost->description = 'Update own post';
$updateOwnPost->ruleName = $rule->name;
$auth->add($updateOwnPost);
// "updateOwnPost" will be used from "updatePost"
$auth->addChild($updateOwnPost, $updatePost);
// allow "author" to update their own posts
$auth->addChild($role, $updateOwnPost);
Now if all goes well and you can add a rule by running the code above
Remember You need to check the updatePost
rule in the check Yii::$app->user->can()
and not updateOwnPost
and pass the Post
model instance along as the second parameter
Like this
if (\Yii::$app->user->can('updatePost', ['post' => $post])) {
// update post
}
About The code Placement in the current application
If you want to have a separate interface where you can add create all with a form then you can follow dektrium-rbac
code available already where it provides complete crud that you can use according to your own requirements.
For the reference see below
Note: if you have a lot of controllers and you want to associate this rule with every update action inside the controllers (Given that all the associated models have the created_by
field) then you might go for the console\Controller
and run such processes via console, so that every new controller/update
can be associated with the rule repeating the above process inside a loop. For the console controller usage in basic-app see here