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 ...
随机推荐
- cordova 开发 ios app 简要流程
1 安装node.js环境 官网: http://nodejs.org/ 点击[install],会下载mac的安装包.正常安装即可 2 安装cordova:npm install -g cordo ...
- html 表格的一些属性设置
第一种:单元格跨行 第二种:单元格间距 第三种:带有标题的表格 第四种:带标题的表格
- 转:Windows版本判断大全
/***************************************************************************** Operating System Vers ...
- 用Webstorm 运行React-native 工程时,出错:xcrun: error: unable to find utility "instruments", not a developer tool or in PATH
解决方法:在 终端执行如下命令 sudo xcode-select -s /Applications/Xcode.app/Contents/Developer/ 注意:前提是你已经安装了xcode
- 解析angularjs中的绑定策略
一.首先回顾一下有哪些绑定策略? 看这个实在是有点抽象了,我们来看具体的实例分析吧! 二.简单的Demo实例 @绑定:传递一个字符串作为属性的值.比如 str : ‘@string’ 控制器中代码部分 ...
- 获取apk package name(包名)以及activity name
通过adb 查看最上层成activity名字: linux: adb shell dumpsys activity | grep "mFocusedActivity" window ...
- March 10 2017 Week 10 Friday
If you love life, life will love you back. 爱生活,生活也会爱你. Love life, and it will love you back. All thi ...
- Fiori里花瓣的动画效果实现原理
Fiori里的busy dialog有两种表现形式,一种是下图里的花朵形状,由5个不断旋转的花瓣组成.另一种是下图的3/4个圆环不断旋转的效果. 关于前者的效果,可以看我制作的这个视频.这个视频是手动 ...
- Android 位置服务
原文来自:http://developer.android.com/guide/topics/location/strategies.html 位置策略 注意: 本指南仅限android.locati ...
- 作为PHP开发者请务必了解Composer
Composer是一个非常流行的PHP包依赖管理工具,已经取代PEAR包管理器,对于PHP开发者来说掌握Composer是必须的. 对于使用者来说Composer非常的简单,通过简单的一条命令将需要的 ...