yii 自带RBAC

common:中加

 'authManager' => [
            'class' => 'yii\rbac\DbManager',
            'itemTable' => 'auth_item',
            'assignmentTable' => 'auth_assignment',
            'itemChildTable' => 'auth_item_child',
        ],

yii中自带的四张表:

vendor/yiisoft/yii2/rbac/migrations/schma-mysql.sql

还加一个user表:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `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;

Rbac控制器

<?php
namespace backend\controllers;

use backend\models\Rbac;
use yii\web\Controller;
use yii;
use \yii\db\Query;
use \yii\data\Pagination; 
use app\models\AuthItem;
use app\models\Auth;

class RbacController  extends Controller
{

    public function init(){
        $this->enableCsrfValidation = false;
        $session=\yii::$app->session;
        $session->open();
    }


    //在控制器中写一个actionpower 跳到我们添加权限的表单页面
    public function actionIndex(){
        $model = new Rbac();
        return $this->render('index',['model'=>$model]);
    }
    //然后在控制器里把权限入库
    public function actionPower()
    {
        $item = \Yii::$app->request->post('Rbac')['power'];
        $auth = Yii::$app->authManager;
        $createPost = $auth->createPermission($item);
        $createPost->description = '创建了 ' . $item . ' 权限';
        $auth->add($createPost);
        return $this->redirect('?r=rbac/role');
    }
    //创建一个就角色的表单
    public function actionRole(){
        $model = new Rbac();
        return $this->render('role',['model'=>$model]);
    }
    //添加角色入库
    public function actionAddrole(){
        $item = \Yii::$app->request->post('Rbac')['role'];
        $auth = Yii::$app->authManager;
        $role = $auth->createRole($item);
        $role->description = '创建了 ' . $item . ' 角色';
        $auth->add($role);

        return $this->redirect('?r=rbac/rp');
    }
    //然后给角色分配权限

    public function actionRp(){
        $model = new Rbac();
        $role =  AuthItem::find()->where('type=1')->asArray()->all();
        foreach($role as $value){
            $roles[$value['name']] = $value['name'];
        }
        $power=  AuthItem::find()->where('type=2')->asArray()->all();
        foreach($power as $value){
            $powers[$value['name']] = $value['name'];
        }

        return $this->render('rp',['model'=>$model,'role'=>$roles,'power'=>$powers]);
    }
    //然后入库

    public function actionEmpowerment(){
        $auth = Yii::$app->authManager;
        $data = \Yii::$app->request->post('Rbac');
        $role = $data['role'];
        $power = $data['power'];

        foreach($role as $value){
            foreach($power as $v){
                $parent = $auth->createRole($value);

                $child = $auth->createPermission($v);
                //var_dump($child);
                $auth->addChild($parent, $child);
            }
        }
        return $this->redirect('?r=rbac/fenpei');
    }
    //然后给用户分配角色

    public function actionFenpei(){
            $models = new Rbac();
            $sql = 'select name from auth_item where type=1';
            $role =\Yii::$app->db->createCommand($sql)->queryAll();
            foreach($role as $v){
                $roles[$v['name']] = $v['name'];
            }
            $sql1 = 'select id,username from user';
          //  print_r($sql1);die;

            $power =\Yii::$app->db->createCommand($sql1)->queryAll();

            foreach($power as $vv){
                $user[$vv['id']] = $vv['username'];
            }
            return $this->render('fenpei',['role'=>$roles,'user'=>$user,'model'=>$models]);


    }
    //将给用户分配的角色入库
    public function actionEmpower()
    {
        $items= Yii::$app->request->post();

        $role = $items['Rbac']['role'];
        foreach($items['Rbac']['role'] as $value ){
            $auth = Yii::$app->authManager;

            $parent = $auth->createRole($role);
            $child = $auth->createPermission($value);
            $auth->addChild($parent, $child);
        }
        return $this->redirect('fenpei');
    }


    public function actionUr(){
        $auth = Yii::$app->authManager;
        $data = \Yii::$app->request->post('Rbac');
        //print_r($data);die;
        $role = $data['role'];
        $power = $data['user'];

        foreach($role as $key=>$val) {
               foreach ($power as $v) {
                $reader = $auth->createRole($val);
                $auth->assign($reader, $v);
            }
        }
    }


        //写到你其他的控制器就可以了
        //你给登陆是把用户id存进session就行了
        //  $session = yii::$app->session;
        //    $session->set('id',$db[0]['id']);
         //   $session->set('username',$db[0]['username']);
   /* public function beforeAction($action)
    {
        $sql="select user_id,child from auth_assignment join auth_item_child on auth_assignment.item_name=auth_item_child.parent where user_id='".$_SESSION['id']."'";
        $role =\Yii::$app->db->createCommand($sql)->queryAll();
        $arr=array_column($role,'child');
        $action=$_REQUEST['r'];
        if(in_array($action, $arr)){
            return true;
        }else{
            throw new \yii\web\UnauthorizedHttpException('对不起,您现在还没获此操作的权限');
        }
    }*/
}

model:

Auth.php

<?php
namespace app\models;

class Auth extends \yii\base\Model
{
    
    public static function tableName()
    {
        return 'auth_item';
    }

    public function rules()
    {
        return [

        ];
    }




    public function attributeLabels()
    {
        return [
            'name'=>'名称',
            'type'=>'分类',
        ];
    }

        //获取角色
     public  function  Rule_list(){
          $sql = 'select * from  `auth_item` where `type`=1 ';
         return \yii::$app->db->createCommand($sql)->queryAll();//执行
     }

       // 给管理员赋角色
    public function  Add_assign($item_name,$user_id){
         $time = time();
          $sql = "insert into auth_assignment (`item_name`,`user_id`,`created_at`) VALUE ('$item_name','$user_id',$time)";
         return \yii::$app->db->createCommand($sql)->query();//执行
       }



     //添加角色
      public function  Add_rule($data){
          $this->setAttributes($data);
          return $this->insert();
      }

      //获取权限
     public function Items_list(){
         $sql = 'select * from  `auth_item` where `type`=2 ';
         return \yii::$app->db->createCommand($sql)->queryAll();//执行
     }

    // 给角色分配权限
    public  function  Item_child($rule,$items){
         $sql = "insert into `auth_item_child` (`parent`,`child`) VALUE ('$rule','$items')";
        return \yii::$app->db->createCommand($sql)->query();//执行
    }

}

AuthItem.php

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "auth_item".
 *
 * @property string $name
 * @property integer $type
 * @property string $description
 * @property string $rule_name
 * @property resource $data
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property AuthAssignment[] $authAssignments
 * @property AuthRule $ruleName
 * @property AuthItemChild[] $authItemChildren
 * @property AuthItemChild[] $authItemChildren0
 * @property AuthItem[] $children
 * @property AuthItem[] $parents
 */
class AuthItem extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'auth_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'type'], 'required'],
            [['type', 'created_at', 'updated_at'], 'integer'],
            [['description', 'data'], 'string'],
            [['name', 'rule_name'], 'string', 'max' => 64],
            [['rule_name'], 'exist', 'skipOnError' => true, 'targetClass' => AuthRule::className(), 'targetAttribute' => ['rule_name' => 'name']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Name',
            'type' => 'Type',
            'description' => 'Description',
            'rule_name' => 'Rule Name',
            'data' => 'Data',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthAssignments()
    {
        return $this->hasMany(AuthAssignment::className(), ['item_name' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRuleName()
    {
        return $this->hasOne(AuthRule::className(), ['name' => 'rule_name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthItemChildren()
    {
        return $this->hasMany(AuthItemChild::className(), ['parent' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthItemChildren0()
    {
        return $this->hasMany(AuthItemChild::className(), ['child' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChildren()
    {
        return $this->hasMany(AuthItem::className(), ['name' => 'child'])->viaTable('auth_item_child', ['parent' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParents()
    {
        return $this->hasMany(AuthItem::className(), ['name' => 'parent'])->viaTable('auth_item_child', ['child' => 'name']);
    }
}

Rbac.php:

<?php
namespace backend\models;
class Rbac extends \yii\base\Model
{
    public $power;
    public $role;
    public $user;

    public function rules()
    {
        return [
            // 在这里定义验证规则
        ];
    }

    public function attributeLabels()
    {
        return [
            'user'=>'用户',
           'power'=>'权限',
            'role'=>'角色',
        ];
    }

}<?php
namespace backend\models;
class Rbac extends \yii\base\Model
{
    public $power;
    public $role;
    public $user;

    public function rules()
    {
        return [
            // 在这里定义验证规则
        ];
    }

    public function attributeLabels()
    {
        return [
            'user'=>'用户',
           'power'=>'权限',
            'role'=>'角色',
        ];
    }

}

User.php:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $role
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
            [['role', 'status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'password_reset_token' => 'Password Reset Token',
            'email' => 'Email',
            'role' => 'Role',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }
}

view:rbac/index.php

<?php
/**
 * Created by PhpStorm.
 * User: jinlei
 * Date: 2017/2/16
 * Time: 10:06
 */

use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
    'action'=>'?r=rbac/power',
    'method'=>'post',
]) ?>
    <?= $form->field($model, 'power') ?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('添加权限', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>

rbac/fenpei

<?php
/**
 * Created by PhpStorm.
 * User: jinlei
 * Date: 2017/2/16
 * Time: 14:05
 */

use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
    'action'=>'?r=rbac/ur',
    'method'=>'post',
]) ?>
<?= $form->field($model, 'user')->checkboxList($user) ?>
<?= $form->field($model, 'role')->checkboxList($role) ?>


    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('提交', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>

rbac/role.php

<?php
/**
 * Created by PhpStorm.
 * User: jinlei
 * Date: 2017/2/16
 * Time: 13:52
 */

use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
    'action'=>'?r=rbac/addrole',
    'method'=>'post',
]) ?>
<?= $form->field($model, 'role') ?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('添加角色', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>

rbac/rp.php

rp.php<?php
/**
 * Created by PhpStorm.
 * User: jinlei
 * Date: 2017/2/16
 * Time: 14:05
 */

use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
    'action'=>'?r=rbac/empowerment',
    'method'=>'post',
]) ?>
<?= $form->field($model, 'role')->checkboxList($role) ?>
<?= $form->field($model, 'power')->checkboxList($power) ?>

    <div class="form-group">


        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('提交', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>

 

posted @ 2017-05-15 11:41  穷帅哥依然纵横一方  阅读(175)  评论(0编辑  收藏  举报