M
M
Makar Gerasimov2016-10-05 18:44:19
Yii
Makar Gerasimov, 2016-10-05 18:44:19

Automatic permission checking?

Hello, tell me please. I set up rbac in such a way that each user, in addition to the role, has a separate permission to some kind of action.
Is there an option to automate the permission check instead of writing it in every action function?

if( ! Yii::$app->user->can('nameAction') ) {
     return false;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-10-06
@MacFiss

if you check with can in each action, there are two options to solve this problem:
1. Check access to the action with AccessControl at the controller/module level, for example:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['index'],
                    'roles' => ['nameAction'], // тут указываем название Permission
                ],
            ],
        ],
    ];
}

this option, of course, does not automate the check very much. all the same, manually it is necessary to prescribe which action which Permission corresponds to, but it makes the code less dependent.
2. Check access to the action before executing the action at the beforeAction level of the controller (or its parent), for example:
public function beforeAction($action)
{ 
    if (parent::beforeAction($action) === false) {
        return false;
    }
    if (Yii::$app->user->can($this->module->id . '.' . $this->id . '.' . $action->id)) {
        return true;
    } else {
        throw new \yii\web\ForbiddenHttpException();
    }    
}

Accordingly, with this approach, Permission should have names in the format "<module name>.<controller name>.<action name>"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question