rbac and rule

I’ve worked with Yii2 RBAC quite alot and understand most of it. But still have some questions about permission to permission relation and permission-rule

6743

rbac-hierarchy-2.png

  1. First question is about permission. Please see the screenshot above

Assume we are talking about user John

if ‘updateOwnPost’ is the parent of ‘updatePost’, and ‘updateOwnPost’ belong to ‘Author’ role,

now when we ask




if (\Yii::$app->user->can('updatePost')) {

    // create post

}



should it return true because ‘updatePost’ is a child of ‘updateOwnPost’ which belongs to ‘author’ role ?

  1. Why do I need to create a new permission ‘updateOwnPost’ and add ‘AuthorRule’ to it ? Can I just add ‘AuthorRule’ to ‘updatePost’ ?

This requires some tests because I’m only 95% sure but:

  1. Yes if he wants to update his own post.

  2. You can just add it but:

  • it will check for author every time which takes more time

  • with two connected permissions you can use updatePost for both roles without worrying if user is author of the post

  1. It depends on which value the “AuthorRule” returns when the parameter ‘post’ is empty.

So, if the rule is defined in the same way as in the example of the guide, it returns false.

Note that “can(‘updatePost’)” is called with a parameter ‘post’ in the example of the guide:




if (\Yii::$app->user->can('updatePost', ['post' => $post])) {

    // update post

}



The ‘post’ parameter is ignored in ‘updatePost’, but will be passed to ‘updateOwnPost’ to be checked by “AuthorRule”.

In order to allow John to update a post, you have to have a way from “updatePost” to “John” following the arrows. “updatePost” has a way to “admin”, but there’s no way from “admin” to “John”. So we have to follow the route of “updatePost” -> "updateOwnPost -> “author” -> “John”. And in the “updateOwnPost”, the rule is checked to see if the post is his own. If the post is his own, then he will be allowed to update it. But other "author"s like “Bizley” and “softark” are not allowed because the rule returns false and can’t proceed to “author”.

  1. It’s because we want to have a role “admin” who can update any post without considering its author, and a normal role “author” who can update only the posts that he/she has created.

If you add “AuthorRule” to “updatePost”, either “admin” can not update other persons’ posts, or any “author” can update any posts, depending on how you specify the rule and how you call “can()” method.

thanks guys. i got it now.