yii 权限RBAC

来源:互联网 发布:管材销售 知乎 编辑:程序博客网 时间:2024/06/01 10:25

在yii库中有个文件夹, 

/vendor/yiisoft/yii2/rbac

这个文件夹里的文件就是权限相关的代码

yii权限需要4张表: 在DbManager.php中有提到

auth_item: 存放授权条目(译者注:即角色[type=>2]和权限[type=>1])
auth_item_child: 存放授权条目的层次关系
auth_assignment: 存放授权条目对用户的指派情况
auth_rule: 存放规则


要使用权限,需要在配置文件中配置:

'authManager' => [            'class' => 'yii\rbac\DbManager',        ],

然后就是建立权限:

建立前置操作,我用的是高级版,所有我是在backend文件夹下建立了文件夹behaviors和文件PermissionBehavior,代码如下:


namespace backend\behaviors;use yii;use yii\base\Behavior;use yii\web\Controller;use yii\web\ForbiddenHttpException;use yii\helpers\Url;class PermissionBehavior  extends Behavior{public $actions = [];public function events(){return [Controller::EVENT_BEFORE_ACTION => 'beforeAction',];}/** *  * @param \yii\base\ActionEvent $event * @throws ForbiddenHttpException * @return boolean */public function beforeAction($event){if(Yii::$app->user->isGuest){            return Url::to(['site/login']); //登陆验证        }$controller = $event->action->controller->id; //获取到控制器$action = $event->action->id; //获取到action//验证权限$access = $controller . '::' . $action;  //权限name$auth = Yii::$app->authManager;//添加默认权限if (!$a=$auth->getPermission($access)) {      $a = $auth->createPermission($access);      $a->description = '创建了 ' .$access. ' 许可';      $auth->add($a);     }     //超级管理员不需要验证权限     if(Yii::$app->user->id == 1){     return true;     }     if(!Yii::$app->user->can($access)){     throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));     }     return true;}}



然后再控制器中使用,如我的是基础控制器中使用: BaseController.php


public function behaviors()    {        return [            \backend\behaviors\PermissionBehavior::className(),             'access' => [                'class' => AccessControl::className(),                'rules' => [                    [                        'actions' => ['index', 'create', 'update', 'delete', 'ajax-child', 'upload'],                        'allow' => true,                        'roles' => ['@'],                    ],                ],            ],            'verbs' => [                'class' => VerbFilter::className(),                'actions' => [                    'delete' => ['POST'],                ],            ],        ];    }


接下来是创建角色

首先我们需要获取到所有角色:

在AuthItemController.php中的index获取到所有角色并显示出来:



获取角色:

public function actionIndex()    {        $dataProvider = new ActiveDataProvider([            'query' => AuthItem::find()->where(['type'=>1]),        ]);        return $this->render('index', [            'dataProvider' => $dataProvider,        ]);    }


添加角色:

public function actionCreate()    {        $model = new AuthItem();        $authManager = \Yii::$app->authManager;        if ($model->load(Yii::$app->request->post()) && $model->save()) {            $rules = \Yii::$app->request->post('rules');            $this->addRole($authManager, $model->name, $rules); //角色与权限的关系            return $this->redirect(['index']);        } else {            $rules = $model->getRules();            $user_rules = [];            return $this->render('create', [                'model' => $model,                'rules' => $rules,                'user_rules' => $user_rules,            ]);        }    }



添加角色表单:

<?php $form = ActiveForm::begin(); ?>    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>    <?= $form->field($model, 'type')->hiddenInput(['value'=>1])->label(false) ?>    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>    <div class="rules-list">    <?php foreach ($rules as $key => $val): ?>    <dl class="clearfix">    <?php foreach ($val as $k => $v): ?>    <dd><?= Html::checkbox('rules[]', in_array($v['name'], $user_rules), ['value' => $v['name'], 'label'=>$v['title']]); ?></dd>    <?php endforeach ?>    </dl>    <?php endforeach ?>    </div>





修改角色:

public function actionUpdate($id)    {        $model = $this->findModel($id);        $authManager = \Yii::$app->authManager;        if ($model->load(Yii::$app->request->post()) && $model->save()) {            $rules = \Yii::$app->request->post('rules');            $this->addRole($authManager, $model->name, $rules);            return $this->redirect(['index']);        } else {            $rules = $model->getRules();            $user_rules = $authManager->getPermissionsByRole($model->name);            $user_rules = array_keys($user_rules);            return $this->render('update', [                'model' => $model,                'rules' => $rules,                'user_rules' => $user_rules,            ]);        }    }




接下来是为用户分配角色,yii是可以一个用户分配多个角色的,不过一般的开发中还是一个用户对应于一个角色。


添加管理员:

public function actionCreate()    {        $model = new Admin();                if (Yii::$app->request->post()) {            $posts = Yii::$app->request->post();            if($posts['Admin']['password'] != $posts['Admin']['re_password']){                return $this->redirect(['create']);            }            //密码加密            $posts['Admin']['password'] = $model->setPassword($posts['Admin']['password']);            $model->load($posts);             $model->save();            $item_name = $posts['Admin']['role'];            $authAssignmentModel = new AuthAssignment();            $authAssignmentModel->item_name = $item_name; //角色            $authAssignmentModel->user_id = $model->id; // 用户id            $authAssignmentModel->created_at = time();            $authAssignmentModel->save();            return $this->redirect(['index']);        }                $roles = AuthItem::find()->where(['type'=>1])->all();        $roles = ArrayHelper::map($roles, 'name', 'name');        return $this->render('create', [            'model' => $model,            'roles' => $roles,        ]);    }


修改管理员:


public function actionUpdate($id)    {        $model = new Admin();        $model = $this->findModel($model, $id);        if (Yii::$app->request->post()) {            $posts = Yii::$app->request->post();            if(!empty($posts['Admin']['old_password']) && !$model->validatePassword($posts['Admin']['old_password'])){                return $this->redirect(['update', 'id'=>$id]);            }            if(!empty($posts['Admin']['password'])){                if($posts['Admin']['password'] != $posts['Admin']['re_password']){                    return $this->redirect(['update', 'id'=>$id]);                }else{                    $posts['Admin']['password'] = $model->setPassword($posts['Admin']['password']);                }            }            $model->load($posts);             $model->save();            $item_name = $posts['Admin']['role'];            $authAssignmentModel = new AuthAssignment();            $authAssignmentModel->item_name = $item_name;            $authAssignmentModel->user_id = $model->id;            $authAssignmentModel->created_at = time();            $authAssignmentModel->save();            return $this->redirect(['index']);        }        $roles = AuthItem::find()->where(['type'=>1])->all();        $roles = ArrayHelper::map($roles, 'name', 'name');         return $this->render('update', [                'model' => $model,                'roles' => $roles,            ]);    }



原创粉丝点击