RBAC for basic yii2 template

﹥>﹥吖頭↗ 提交于 2019-12-24 13:59:20

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/27542907/rbac-for-basic-yii2-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!