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() ?>
yii 自带RBAC的更多相关文章
- [Yii][RBAC]Yii中应用RBAC完全指南
开端筹办 Yii供给了强大的设备机制和很多现成的类库.在Yii中应用RBAC是很简单的,完全不须要再写RBAC代码.所以筹办工作就是,打开编辑器,跟我来. 设置参数.建树数据库 在设备数组中,增长以下 ...
- Yii中使用RBAC完全指南
开始准备 Yii提供了强大的配置机制和很多现成的类库.在Yii中使用RBAC是很简单的,完全不需要再写RBAC代码.所以准备工作就是,打开编辑器,跟我来.设置参数.建立数据库 在配置数组中,增加以下内 ...
- Yii 自带的分页实例
yii自带的分页很好用,简单的几行代码就能把分页搞出来,唯一恼火的是只能写在controller中,所以有时候controller中的方法有点臃肿.废话少说,上代码上图. 一.代码实例: 1.控制器中 ...
- Yii中使用RBAC全然指南
本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群. 希望光临本博客的人能够进来交流. ...
- YII框架实现 RBAC
(1).在 common\config\main.php添加 'components' => [ ’authManager’ => [ ’class’ => ...
- Yii 框架的Rbac [权限控制]
转载自 xmlife 的博客 : http://blog.csdn.net/xmlife/article/details/50733451 1.首先我们要在配置文件的组件(component)里面配置 ...
- shell 带签名请求,yii 处理带签名的请求
处理请求 class TestController extends Controller { public function init() { if(!YII_ENV_DEV){ throw new ...
- YII 自带验证码实现
共三步,分别controllers,models,views各一层添置一行代码即可实现 第一步在controllers添加 public function actions() { return arr ...
- yii加载自带验证码的方法
Yii的源码包里面是自带有验证码的相关类的,因此在使用验证码的时候无需再加载外部验证码类来助阵了.下面本文将介绍一下如何在项目中加载Yii自带的验证码功能. 具体分三步: (1)在需要加载验证码的co ...
随机推荐
- wxpython 设置鼠标样式
鼠标指针被设置为放大镜样式.可用的鼠标指针样式有: wx.CURSOR_ARROWwx.CURSOR_RIGHT_ARROWwx.CURSOR_BLANKwx.CURSOR_BULLSEYEwx.CU ...
- PHP接口对方(C#)接收不到数据?ContentLength=-1
工作时遇到的问题.浏览器可以查看到json数据,但是对方死活收不到数据. 最后发现发现ContentLength=-1. 找到问题:为什么.NET程序下载获得的ContentLength=-1? 摘抄 ...
- asyncio标准库7 Producer/consumer
使用asyncio.Queue import asyncio import random async def produce(queue, n): for x in range(1, n + 1): ...
- java实现多文件上传01
1.html代码 <html> <head> <link rel="stylesheet" type="text/css" hre ...
- Windows装系统
这几天电脑频繁崩溃,自己尝试着装了几次系统,遇到一些问题.有的解决了,有的没解决.将其一一记录在这里,作为经验参考. 自己以前最常用的方式是直接通过ultraiso将IOS文件解压到到U盘,会将U盘做 ...
- 用AutoHotkey一键完成Xmind里的几个功能
F5一键添加超链接(类型为主题),常规步骤:Ctrl_h打开窗口,点击[主题],激活光标到输入框. Ctrl-i一键添加截取的图片,常规步骤是:打开画图→粘贴→保存图片为文件→Xmind里Ctrl-i ...
- 四、获取远程URL图片
#!/usr/bin/python # -*- coding: UTF-8 -*- import re import urllib def getHtml(url): page = urllib.ur ...
- May 09th 2017 Week 19th Tuesday
Everything you see exists together in a delicate balance. 世上所有的生命都在微妙的平衡中生存. A delicate balance? Can ...
- [EffectiveC++]item30:Understand the ins and outs of inlining
- C语言 字符串处理函数
#include <stdio.h> #include <string.h> // strlen void test() { // 测量字符串常量的字符长度(不包括\0这个字符 ...