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

时间: 2024-10-05 22:37:40

YII框架自带RBAC的相关文章

YII框架源码分析(百度PHP大牛创作-原版-无广告无水印)

                        YII 框架源码分析             百度联盟事业部--黄银锋   目 录 1. 引言 3 1.1.Yii 简介 3 1.2.本文内容与结构 3 2.组件化与模块化 4 2.1.框架加载和运行流程 4 2.2.YiiBase 静态类 5 2.3.组件 6 2.4.模块 9 2.5 .App 应用   10 2.6 .WebApp 应用   11 3.系统组件 13 3.1.日志路由组件  13 3.2.Url 管理组件  15 3.3.异常

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 还加一个

php的yii框架下开发环境xampp,vim,xdebug,DBGp的搭建

php的yii框架下开发环境xampp,vim,xdebug,DBGp的搭建 选择Linux桌面环境Deepin2014.1下开发网站的理由很简单,能截图,有搜狗输入法,可以WPS文档记录,终端下复制粘贴很容易,相比ubuntu,fedora死机次数少了,对,就是不用折腾,自带的. 先说vim和DBGp插件. Deepin2014.1简体中文,自带的vim7.4版本,很多配置已经很适合大陆的人使用了,比如Php和Python的调试支持等,不需要重新编译了.可以节省不少步骤.这里提供一个vim的配

YII框架分析笔记5:控制器和动作

CBaseController是控制器和挂件的基类,主要提供了视图渲染,挂件,剪辑.片段缓存等方法,CController是所有应用中自定义控制器的基类. 创建动作 [php] view plaincopy public function run($actionID) { if(($action=$this->createAction($actionID))!==null) { if(($parent=$this->getModule())===null) $parent=Yii::app()

YII框架分析笔记3:表单模型和验证

表单模型CFormModel绝大部分继承CModelCModel,由于表模型数据不需要持久化,所以主要在验证操作上.下面以框架脚手架生成的网站登录为例说明表单模型. [php] view plaincopy //模型中的验证规则 public function rules() { return array( array('username, password', 'required'), array('rememberMe', 'boolean'), array('password', 'aut

yii框架数据库操作数据访问对象(DAO)简单总结

Yii提供了强大的数据库编程支持.Yii数据访问对象(DAO)建立在PHP的数据对象(PDO)extension上,使得在一个单一的统一的接口可以访问不同的数据库管理系统(DBMS).使用Yii的DAO开发的应用程序可以很容易地切换使用不同的数据库管理系统,而不需要修改数据访问代码.Yii 的Active Record( AR ),实现了被广泛采用的对象关系映射(ORM)办法,进一步简化数据库编程.按照约定,一个类代表一个表,一个实例代表一行数据.Yii AR消除了大部分用于处理CRUD(创建,

使用Yii框架完整搭建网站流程入门

下载地址: http://www.yiiframework.com/ http://www.yiichina.com/ 由美籍华人薛强研究而出, Yii 这个名字(读作易(Yee))代表 简单(easy), 高效(efficient)和可扩展(extensible). 基于MVC,纯OOP,强大 基本配置要求:数据库:mysql,php5.0.1以上:pdo,[图片等需开启gd库模块] 下载完成,解压后,通过127.0.0.1或localhost访问其文件夹,可以查看requirements文件

Yii的自带缓存的使用

Yii的自带缓存都继承CCache 类, 在使用上基本没有区别缓存基础类 CCache 提供了两个最常用的方法:set() 和 get().要在缓存中存储变量 $value,我们选择一个唯一 ID 并调用 set() 来存储它: Yii::app()->cache->set($id, $value); 被缓存的数据会一直保留在缓存中,直到因一些缓存策略而被删除(比如缓存空间满了,删除最旧的数据).要改变这一行为,我们还可以在调用 set() 时加一个过期参数,这样数据过一段时间就会自动从缓存中

Yii框架 CURD

1.Yii框架的sql语句 说明:CDbCommand表示一个针对数据库执行的SQL语句 2.相关连接 yii连接:http://www.php100.com/manual/yii/CDbCommand.html 源代码:framework/db/CDbCommand.php 3.调用createCommand() 方法 (1)它通常通过调用CDbConnection::createCommand创建 (2)要执行一条非查询的SQL(如:insert,delete,update),调用execu