Yii2 RBAC Rule Feedback / Message

This is a question about using RBAC in Yii2.

So far, I have found that it works reasonably well and satisfactorily, but there is one key function that I am missing: the Yii2 Rules ability to provide “feedback” is similar to the way Yii2 Rules set error messages to explain why the check doesn’t done. I am looking for a way to provide some feedback on why permission was not granted.

In particular, the can () method returns a boolean type, which is good, but when checking the permission, we have no idea why the user was not specifically granted this specific permission.

To give a more practical example. Say we are trying to determine if the current user can post a comment. Usually we will do something like this:

if (Yii::$app->user->can('postComment',['comment'=>$comment])) { $comment->post(); } else { throw new ForbiddenHttpException('Sorry m8, you cant do this. No idea why tho!'); } 

It works fine, but as shown in the example, we really don't know why the user cannot post a comment. There can be any number of reasons, for example, because the stream is blocked or because they do not have permission to publish in a certain category or because they do not have a sufficiently high reputation, etc. But we want to tell the user why! So my question is: how do we get this feedback from Yii2 RBAC?

+5
source share
3 answers

So basically all I did was add

 'message' => 'Current password cannot be blank.' 

to my rules.

Make sure that you share the correct rules, so you will not receive this message in several fields where it does not make sense. Also, make sure that you add it to the “required” rule if you do not want this message to be displayed when it was a different rule.

Hope this helps you guys since I spent too much time searching.

+1
source

You would like to create your own AccessRule and set message exceptions from your scripts by overriding the current methods in this class. matchRole is a method that you would redefine. Yii2 does not have this place, so you have to flip your own AccessRule to do this.

Then after creating it, attach it to your controllers:

 public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'ruleConfig' => [ 'class' => 'app\components\AccessRule' ], 'rules' => [ /* my normal rules */ ], ], ]; } 
0
source

still struggling with this ...

so .. i just found this

 yii\filters\AccessControl::$denyCallback 

with signature

 function ($rule, $action) 

where $rule is a rule that forbids the user, may be null if access is denied, because none of the rules matches.

so it’s possible in Rule to create a function that will return an error message. Then create a denyCallback that calls these functions.

0
source

Source: https://habr.com/ru/post/1246223/


All Articles