接上一节 基于yii2的blog系统开发8:
视频地址:https://v.youku.com/v_show/id_XMTgwODg1NzIzMg==.html
高级模版自动生成的User模型里面没有加email验证规则,建议用gii重新生成比对下,把相应代码补全.
在yii2中提供两种授权管理途径
(1)ACF存取控制授权(较为简单,适合访客权限设置简单的情景)
(2)RBAC基于角色的存取授权控制(较为复杂,适合博客,论坛等大型网站)

第十五步 ACF授权

acf即存取控制过滤器,控制器里引用:
use yii\filters\AccessControl
改写behaviors方法:

public function behaviors()
 {
     return [
        'access'=>[
          'class' => AccessControl::className(),
            //允许未登录的游客访问action ID为 index login的action
          'rules' => [
                [
                  'actions' => ['index','login'],
                   'allow' => true,
                   'roles' => ['?'],//?表示未登录的游客
                ],
              //只允许已经登录的用户访问action ID为contact about的action 其他禁止
                    [
                   'actions' => ['contact','about'],
                   'allow' => true,
                   'roles' => ['@'],// @表示已经登录的用户
                ]
                 ],
            ],
           ];
 }

更多详细设置参考:
https://blog.csdn.net/aozeahj/article/details/52404755

第十六步 RBAC授权

1.修改common/config/main.php:

<?php
return [
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        //添加这个代码
        'authManager'=>[
            'class'=>'yii\rbac\DbManager',
        ],
    ],

];

2.在项目根目录执行命令,在数据库创建四张rbac的表:

./yii migrate --migrationPath=@yii/rbac/migrations

3.在console/controllers/下新建RbacController.php文件,主要目的为利用authManager组件的api来创建授权表的初始数据:

<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
    public function actionInit()
    {
        $auth = Yii::$app->authManager;
        // 添加 "createPost" 权限
        $createPost = $auth->createPermission('createPost');
        $createPost->description = '新增文章';
        $auth->add($createPost);
        // 添加 "updatePost" 权限
        $updatePost = $auth->createPermission('updatePost');
        $updatePost->description = '修改文章';
        $auth->add($updatePost);
        // 添加 "deletePost" 权限
        $deletePost = $auth->createPermission('deletePost');
        $deletePost->description = '删除文章';
        $auth->add($deletePost);

        // 添加 "approveComment" 权限
        $approveComment = $auth->createPermission('approveComment');
        $approveComment->description = '审核评论';
        $auth->add($approveComment);

        // 添加 "postadmin" 角色并赋予 "updatePost" “deletePost” “createPost”
        $postAdmin = $auth->createRole('postAdmin');
        $postAdmin->description = '文章管理员';
        $auth->add($postAdmin);
        $auth->addChild($postAdmin, $updatePost);
        $auth->addChild($postAdmin, $createPost);
        $auth->addChild($postAdmin, $deletePost);

        // 添加 "postOperator" 角色并赋予  “deletePost” 
        $postOperator = $auth->createRole('postOperator');
        $postOperator->description = '文章操作员';
        $auth->add($postOperator);
        $auth->addChild($postOperator, $deletePost);

        // 添加 "commentAuditor" 角色并赋予  “approveComment”
        $commentAuditor = $auth->createRole('commentAuditor');
        $commentAuditor->description = '评论审核员';
        $auth->add($commentAuditor);
        $auth->addChild($commentAuditor, $approveComment);
        // 添加 "admin" 角色并赋予所有其他角色拥有的权限
        $admin = $auth->createRole('admin');
        $admin->description = '系统管理员';
        $auth->add($admin);
        $auth->addChild($admin, $postAdmin);
        $auth->addChild($admin, $commentAuditor);


        // 为用户指派角色。其中 1 和 2 是由 IdentityInterface::getId() 返回的id (译者注:user表的id)
        // 通常在你的 User 模型中实现这个函数。
        $auth->assign($admin, 1);
        $auth->assign($postAdmin, 2);
        $auth->assign($postOperator, 3);
        $auth->assign($commentAuditor, 4);
    }
}

在项目目录下执行命令:
./yii rbac/init
这样数据库里面就有数据了

4.在控制器中执行权限检查,以backend/controllers/PostController.php为例:

use yii\web\ForbiddenHttpException;
public function actionCreate()
    {
        if(!Yii::$app->user->can('createPost')){
            throw new ForbiddenHttpException('对不起,您没有该操作的权限');
        }
        $model = new Post();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

5.写个界面给管理员用户分配权限,主要就是对对应四张表进行crud即可

5.1 backend/views/adminusesr下新建授权页面sq.php:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>

<div class="adminuser-form">
    <?php $form = ActiveForm::begin(); ?>   
<!--?= Html::checkboxList('roles', '选中值数组',['value'=>'label']) ?-->
  <?= Html::checkboxList('roles', $a1,$a2) ?>   
    <div class="form-group">
        <?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>

5.2 用gii生成auth_assignment,auth_item的模型类,然后在backend/controllers/adminusesrController.php中添加权限管理的action,注意这里的函数名和index视图中的权限管理按钮名称对应:

use yii\helpers\ArrayHelper;
public function actionQxgl($id)
    {

        $y1=AuthAssignment::find()->select(['item_name'])->where(['user_id' => $id])->all();
        $y2=yii::$app->db->createCommand("select name,description from auth_item where type=1")->query();

        $a1 = array();
        foreach($y1 as $i){
            //VarDumper::dump($i);exit(0);
            array_push($a1,$i->item_name);
        }

        $a2 = ArrayHelper::map($y2,'name','description');


        if(isset($_POST['roles']))
        {
            AuthAssignment::deleteAll('user_id=:id',[':id'=>$id]);
            $newr=$_POST['roles'];
            $len=count($newr);
            for($i=0;$i<$len;$i++){
                $t = new AuthAssignment();
                $t->item_name=$newr[$i];
                $t->user_id=$id;
                $t->created_at=time();
                $t->save();
            }

            return $this->redirect(["index"]);
        }

        return $this->render('sq', ['id'=>$id,
            'a1' => $a1,'a2' => $a2,
        ]);
    }