RBAC for basic yii2 template

2019-08-14 17:38发布

i want to create an application where only admin can perform all the crud operations but other users can only create and update posts. I did find tutorials based on rbac but only for advanced template but i am using the basic template. I also followed the yii2 guide but i did not understood it very well like executing ./yii rbac/init console command. How do i do it?

标签: php yii2 rbac
1条回答
时光不老,我们不散
2楼-- · 2019-08-14 17:54

first of all create a Helper Class called PermissionHelpers in your model folder:

namespace app\models;
use Yii;

class PermissionHelpers {

    public static function requireAdmin() {

        if(Yii::$app->user->identity->role == 100)
        {
            return true;
        }
        else return false;
    }
} 

Then update your controller with:

// at top with your other use
use yii\filters\AccessControl;
use app\models\PermissionHelpers;


// first function inside the class
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['privateaction1', 'privateaction2'],
            'rules' => [
                [
                    'actions' => ['privateaction1', 'privateaction2'],
                    'allow' => true,
                    'roles' => ['@'],
                    'matchCallback' => function($rule, $action) {
                            return PermissionHelpers::requireAdmin();
                        }
                ],
            ],
        ],
}

And now you need to update yourself in the DB with role = 100, and you're set.

I'm using Advanced template myself, so there might be small changes to the namespaces and such. But it should be fairly easy to figure out. Good luck!

查看更多
登录 后发表回答