好好的五张表在YII2里被搞成了这样(RBAC)

标准RBAC 好好的五张表在YII2里被搞成了这样

auth_item 角色 权限表 type字段 “1” 代表角色 “2” 代表权限
auth_item_child 角色权限关联表, 即角色权限中间表
auth_assignment 用户角色表(也可以直接用户权限表)
auth_rule 规则表
貌似少了个用户表—>本王 自己解决

yii自带数据表 advanced\vendor\yiisoft\yii2\rbac\migrations\schema-mysql.sql

drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
drop table if exists `auth_rule`;
drop table if exists `user`;

create table `auth_rule`
(
   `name`                 varchar(64) not null,
   `data`                 blob,
   `created_at`           integer,
   `updated_at`           integer,
    primary key (`name`)
) engine InnoDB;

create table `auth_item`
(
   `name`                 varchar(64) not null,
   `type`                 smallint not null,
   `description`          text,
   `rule_name`            varchar(64),
   `data`                 blob,
   `created_at`           integer,
   `updated_at`           integer,
   primary key (`name`),
   foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
   key `type` (`type`)
) engine InnoDB;

create table `auth_item_child`
(
   `parent`               varchar(64) not null,
   `child`                varchar(64) not null,
   primary key (`parent`, `child`),
   foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
   foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

create table `auth_assignment`
(
   `item_name`            varchar(64) not null,
   `user_id`              varchar(64) not null,
   `created_at`           integer,
   primary key (`item_name`, `user_id`),
   foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade,
   key `auth_assignment_user_id_idx` (`user_id`)
) engine InnoDB;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `username` varchar(255) NOT NULL COMMENT '用户名',
  `auth_key` varchar(32) NOT NULL COMMENT '自动登陆key',
  `password_hash` varchar(255) NOT NULL DEFAULT '' COMMENT '加密密码',
  `password_reset_token` varchar(255) DEFAULT NULL COMMENT '重置密码token',
  `email_validate_token` varchar(255) DEFAULT NULL COMMENT '邮箱验证token',
  `email` varchar(255) NOT NULL COMMENT '邮箱',
  `role` smallint(6) NOT NULL DEFAULT '10' COMMENT '角色等级',
  `status` smallint(6) NOT NULL DEFAULT '10' COMMENT '状态',
  `avatar` varchar(255) DEFAULT NULL COMMENT '头像',
  `vip_lv` int(11) DEFAULT '0' COMMENT 'vip等级',
  `created_at` int(11) NOT NULL COMMENT '创建时间',
  `updated_at` int(11) NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

然后是对上面表操作的各种类

/advanced/vendor/yiisoft/yii2/rbac/目录下
Item.php 权限或角色类
Role.php 管理角色的类
Permission 控制权限操作的类
Assignment 用户与角色类
Rule 规则类

配置RBAC组件

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

配置好之后就可以调用组件来操作数据表啦

创建一个角色(insert auth_item) ‘type’=1

 $modelRole = \YII::$app->authManager->createRole(null);
        $modelRole->name = "星座大使";
        $modelRole->description = "黄金圣斗士管理者";
        $modelRole->ruleName = null;
        $modelRole->data = null;
        \YII::$app->authManager->add($modelRole);
        \YII::$app->end();

向数据表auth_item插入权限 ‘type=2’

<?php

namespace frontend\controllers;

class RbacController extends BaseController
{
    public function actionCreateitem()
    {
        $temp = [];
        $dir = opendir(dirname(__FILE__));
        while($file = readdir($dir)){
            if($file == "." || $file == ".." || $file == "BaseController.php"){
                continue;
            }
            //类名
            preg_match("/(.*)Controller\.php/", $file, $name);;

            //方法名 actions
            $post = \YII::$app->createControllerByID(strtolower($name[1]));
            $ar_actions = $post->actions();
            $temp_actions = [];
            foreach($ar_actions as $key => $value){
                $temp_actions[] = $name[1]."/".$key;
            }
            //action方法名
            $content = file_get_contents(dirname(__FILE__)."/".$file);
            preg_match_all("/public function action([A-Z][a-zA-Z]+)/", $content, $metch);
            $metch = $metch[1];
            foreach($metch as $key => $value){
                $metch[$key] = $name[1]."/".$value;
            }
            $metch[] = $name[1]."/*";
            $temp = array_merge($metch, $temp_actions);

            //循环插入
            $auth = \YII::$app->authManager;
            foreach($temp as $key => $value){
                if(!$auth->getPermission($value)){

                    $obj = $auth->createPermission($value);
                    $obj->description = $value;
                    $auth->add($obj);
                }
            }
        }

    }

}

给角色分配权限或子角色(insert auth_item_child)

 $auth = \YII::$app->authManager;
        $parent = $auth->getRole("星座大使");
        $childName = "Site/Signup";
        $child = $auth->getRole($childName) ? $auth->getRole($childName) : $auth->getPermission($childName);
        if($child && $auth->canAddChild($parent, $child)){
            $auth->addChild($parent, $child);
        }

给用户添加权限或角色

$item_name = "星座大使";
        $item_obj = $auth->getRole($item_name) ? $auth->getRole($item_name) : $auth->getPermission($item_name);
        $auth->assign($item_obj, \YII::$app->user->getId());

获得一个角色的子角色和权限

$role_and_auth = $auth->getChildren("星座大使");

删除用户所有权限与角色;

$auth->revokeAll(\YII::$app->user->getId());

删除当前角色所有子节点

$auth->removeChildren($role_obj);

获得用户的所有角色

$auth->getRolesByUser(\YII::$app->user->getId());

获取当前用户所有权限

$auth->getPermissionsByUser(\YII::$app->user->getId());

在公共继承控制器中过滤Controller/action的实例化

class BaseController extends Controller{
    public function beforeAction($action){
        if(!parent::beforeAction($action)){
            return false;
        }

        $controller = $action->controller->id;
        $actionName = $action->id;
        if(\YII::$app->user->can($controller."/"."*")){
            return true;
        }

        if(\YII::$app->user->can($controller."/".$actionName)){
            return true;
        }

        throw new \yii\web\UnauthorizedHttpException("403 Forbidden");
    }
}

权限控制中的rule规则类似于linux权限系统的文件系统权限

在要进行权限控制的表中添加user_id字段, 插入记录时填充用户ID

CREATE TABLE `category` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Id',
  `cat_name` varchar(30) NOT NULL COMMENT '分类名称',
  `parent_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '上级分类Id',
  `is_floor` enum('是','否') NOT NULL DEFAULT '否' COMMENT '是否推荐楼层',
  `user_id` int(11) NOT NULL DEFAULT '0' COMMENT '创建此条记录用户ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;

定义一条规则

<?php
namespace frontend\models;

use yii\rbac\Rule;

class AuthorRule extends Rule{
    public $name = "isAuthor"; //规则名称

    public function execute($user, $item, $params){
//        $action = \YII::$app->controller->id;
        var_dump($user); //当前用户ID
        var_dump($item); //用户ID对应的角色或权限obj
        var_dump($params);exit();
        //return true or false;
    }
}

向规则表auth_rule添加一条规则

       $ruleObj = new \frontend\models\AuthorRule();
        $auth = \YII::$app->authManager;
        $auth->add($ruleObj);

在角色与权限(auth_item)表,角色记录(type=1)中rule_name字段添加对应规则名称即可($AuthorRule->name);

  • 用户 查询 角色 查询 权限 => 此时规则添加给角色
  • 用户 查询 权限 此时规则添加给权限

在yii2权限控制里rule规则的使用很诡异, 貌似有缓存, 需要退出当前角色重新登陆才能生效.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值