1. 程式人生 > >Yii RBAC

Yii RBAC

res setattr pro group add ray mtab reat edi

\common\config\main.php或者\backend\config\main.php中加

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

yii中自帶的四張表:

vendor/yiisoft/yii2/rbac/migrations/schma-mysql.sql 復制裏面的內容在mysql中運行

還要自己加一個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‘=>‘角色‘,
        ];
    }

}

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

<?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() ?>

 

Yii RBAC