Yii2 RBAC: which checks should be put into rules

173 views Asked by At

Lets say there is a forum with two kinds of users (admin and user) and admin can close a thread. On some page I need to draw a button to close a thread.

If I model this in RBAC according to http://www.yiiframework.com/doc-2.0/guide-security-authorization.html I have to create roles "adminRole" and "userRole" and a permission "closeThread" and attach that permission to the "adminRole" role. But no one can close a thread that has already been closed. Should a check like that be put into a rule assigned to "closeThread" permission or be kept outside of RBAC specific classes?

Variant 1. The check is in a rule attached to "closeThread" permission:

// Definition of the rule attached to "closeThread" permission:
class CloseThreadRule extends \yii\rbac\Rule
{
    public function execute($user, $item, $params)
    {
        return $params['thread']->is_closed == false;
    }
}

// $thread - is an instance of a class representing thread data
if(\yii::$app->user->can('closeThread', ['thread' => $thread]))
    /* show "Close Thread" button */;

Variant 2. The check is kept outside of RBAC classes:

if($thread->is_closed == false && \yii::$app->user->can('closeThread'))
    /* show "Close Thread" button */;

So which is the proper way to go (variant 1 or variant 2) according to RBAC methodology?

0

There are 0 answers