小巫师 2017-10-10 09:19:08 7128次浏览 9条评论 18 4 0
/**
 * Database schema required by \yii\rbac\DbManager.
 *创建RBAC表
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 *  http://www.yiiframework.com/
 * @copyright 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @since 2.0
 */

drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
drop table if exists `auth_rule`;

 

CREATE TABLE `auth_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `auth_key` varchar(32) NOT NULL,
  `password_hash` varchar(255) NOT NULL,
  `password_reset_token` varchar(255) DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `role` smallint(6) NOT NULL DEFAULT '10',
  `status` smallint(6) NOT NULL DEFAULT '10',
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT charset=utf8;

 

create table `auth_rule`
(
   `name`                 varchar(64) not null,
   `data`                 blob,
   `created_at`           integer,
   `updated_at`           integer,
    primary key (`name`)
) engine InnoDB;

create table `auth_item`
(
   `name`                 varchar(64) not null,
   `type`                 smallint not null,
   `description`          text,
   `rule_name`            varchar(64),
   `data`                 blob,
   `created_at`           integer,
   `updated_at`           integer,
   primary key (`name`),
   foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
   key `type` (`type`)
) engine InnoDB;

create table `auth_item_child`
(
   `parent`               varchar(64) not null,
   `child`                varchar(64) not null,
   primary key (`parent`, `child`),
   foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
   foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

create table `auth_assignment`
(
   `item_name`            varchar(64) not null,
   `user_id`              varchar(64) not null,
   `created_at`           integer,
   primary key (`item_name`, `user_id`),
   foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

/ 以下是代码操作/

<?php


namespace frontend\controllers;

use frontend\models\Form;
use frontend\models\Rbac;
use yii\web\Controller;

class RbacController extends Controller {

    //首页
    public function actionIndex()
    {
        return $this->render("index");
    }

    //创建权限
    public function actionAdd_rule()
    {
        $model = new Form();
        return $this->render("add_rule",['model'=>$model]);
    }
    //权限添加处理
    public function actionRule_add()
    {
        $data = \Yii::$app->request->post("Form");
        $item = $data['username'];

        /*操作核心代码开始*/
        $auth = \Yii::$app->authManager;
        //权限名: action
        $createPost = $auth->createPermission($item);
        //添加描述
        $createPost->description = '创建了 ' . $item . ' 许可';
        $auth->add($createPost);
        /*操作核心代码开始*/

        echo"<script>alert('创建成功');location.href='?r=rbac/index'</script>";
    }

    //添加角色
    public function actionRoles()
    {
        $model = new Form();
        return $this->render("roles",['model'=>$model]);
    }

    //添加角色处理
    public function actionRoles_dd()
    {
        $data = \Yii::$app->request->post("Form");
        $item = $data['username'];

        /*操作核心代码开始*/
        $auth = \Yii::$app->authManager;
        //角色名
        $role = $auth->createRole($item);
        //操作描述
        $role->description = '创建了 ' . $item . ' 角色';
        $auth->add($role);
        /*操作核心代码结束*/

        echo"<script>alert('创建成功');location.href='?r=rbac/index'</script>";
    }

    //给角色分配许可
    public function actionAuth_item()
    {
        /*操作核心代码开始*/
        $model = new Form();
        $mod = new Rbac();
        $data = $mod->auth_item();
        /*操作核心代码结束*/

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

    //给角色分配许可处理
    public function actionAuth_item_dd()
    {
        $data = \Yii::$app->request->post("Form");
        $role='';
        $auth='';
        $reg = array();
        foreach ($data['auth'] as $v)
        {
            $auth=$v;
            foreach ($data['role'] as $key=>$val)
            {
                $role=$val;
                $reg[$role][]=$auth;
            }
        }
        //循环入库,方法太喽.懒得改了,记一下入库代码就行
        foreach ($reg as $k=>$v)
        {
            foreach ($v as $val)
            {

                /*操作核心代码开始*/
                $auth = \Yii::$app->authManager;
                //角色名
                $parent = $auth->createRole($k);
                //权限名
                $child = $auth->createPermission($val);
                $auth->addChild($parent, $child);
                /*操作核心代码结束*/

            }
        }
        echo"<script>alert('给角色分配许可');location.href='?r=rbac/index'</script>";
    }

    //给用户分配角色
    public function actionChild()
    {
        //查询所有角色
        $role = (new \yii\db\Query())
            ->select(['name'])
            ->from("auth_item")
            ->where(['type'=>1])->all();

        $role_new = array();
        foreach ($role as $v)
        {
            $role_new[$v['name']]=$v['name'];
        }
        //查询所有用户
        $user = (new \yii\db\Query())
            ->select(['username','id'])
            ->from("user")
            ->all();
        $user_new = array();
        foreach ($user as $v)
        {
            $user_new[$v['id']]=$v['username'];
        }

        $model = new Form();
       return$this->render("child",['model'=>$model,'role'=>$role_new,'user'=>$user_new]);
    }

    //给用户分配角色处理
    public function actionChild_dd()
    {
        $data = \Yii::$app->request->post('Form');
        $role='';
        $reg = array();
        foreach ($data['role'] as $v)
        {
            foreach ($data['auth'] as $key=>$val)
            {
                $role=$val;
                $reg[$role][]=$v;
            }
        }

        foreach ($reg as $k=>$v)
        {
            foreach ($v as $val)
            {

                /*操作核心代码开始*/
                $auth = \Yii::$app->authManager;
                $reader = $auth->createRole($k);//$k是角色
                $auth->assign($reader, $val);//$val为用户id
                /*操作核心代码开始*/

            }
        }
        echo"<script>alert('用户分配角色成功');location.href='?r=rbac/index'</script>";

    }

   //验证用户是否有权限
    /* 操作核心代码开始,
     * 下面验证方法加入需要验证的控制器里面,或者自己写一个控制器,然后,其它控制器来继承
     * 当该控制器内的方法被执行的时候,会自动验证用户是否有权限操作
     * */
    public function beforeAction($action)
    {
        $action = \Yii::$app->controller->action->id;
        if(\Yii::$app->user->can($action)){
            return true;
        }else{
            throw new \yii\web\UnauthorizedHttpException('对不起,您现在还没获此操作的权限');
        }
    }
    /*操作核心代码开始*/

 

 


}
觉得很赞
您需要登录后才可以评论。登录 | 立即注册