Home  >  Article  >  Database  >  RBAC permission control implementation principle - design of permission table, user table and association table

RBAC permission control implementation principle - design of permission table, user table and association table

灭绝师太
灭绝师太Original
2021-08-31 17:11:596334browse

        RBAC是英文Role-based Access Control的首字母缩写,中文意思是基础角色的权限控制,它是一种思想,根据 RBAC 思想进行数据表设计,更好的完成不同角色的对应的权限控制。

        

        

        如何使用RBAC思想进行数据表的设计 


        如果我们的项目允许一个后台管理用户可能有1个或者2个及2个以上的多个角色,按照下面进行设计:


RBAC permission control implementation principle - design of permission table, user table and association table

    权限菜单表,角色表,用户表是互相独立的。设计表的顺序是权限菜单表,角色表,用户表,用户-角色关联表。

    1. 首先是权限菜单表设计如下:

    注意:权限菜单可以是多级菜单,添加pid字段,方便无限极递归分类。 

RBAC permission control implementation principle - design of permission table, user table and association table

    2. 角色表设计如下:

RBAC permission control implementation principle - design of permission table, user table and association table

    3. 用户表设计如下:

RBAC permission control implementation principle - design of permission table, user table and association table

    4. 最后是用户-角色关联表设计如下:

RBAC permission control implementation principle - design of permission table, user table and association table    

    

    当超级管理员在后台需要添加新用户时,不仅需要insert数据进用户表,也需要在用户-角色表中添加用户和角色的关系。与之对应,删除用户时,也需要将用户-角色表中对应的用户-角色关系删除。

public function add()
    {

        if(request()->isPost()){
            $role_id = input('post.role_id');
            $data = [
                'uname'=>input('post.uname'),
                'pwd'=>password_hash(input('post.pwd'),PASSWORD_BCRYPT),
                'login_ip'=>request()->ip(),
                'status'=>input('post.status'),
                'create_time'=>time(),
            ];
            $uid =  Db::name('users')->insertGetId($data);
            if($uid){
                $data = [
                    'uid'=>$uid,
                    'role_id'=>$role_id
                ];
                $id =  Db::name('users_role')->insertGetId($data);
                if($id)
                {
                    echo 'true';
                    exit;
                }else{
                    echo 'false';
                    exit;
                }
            }else{
                echo 'false';
                exit;
            }
        }else{
            //获取所有角色
            $role = Db::name('auth_role')->field('id,title')->order('id','asc')->where('status',1)->select();
            return view('add',['role'=>$role]);
        }
       
    }

           这样以来我们根据用户登录以后session中储存的uid判断当前登录用户的身份信息,根据获取到的uid查询用户-角色关联表查询到用户的角色id, 然后到角色表获取到该用户可操作的权限菜单。

    封装中间控制器Common.php

<?php
namespace app\admin\controller;
use app\BaseController;
use think\facade\Session;
use lib\Auth;/**权限认证类**/
class Common extends BaseController
{
    public function initialize(){
        $sess_auth  = session(&#39;uid&#39;);
        $uname = session(&#39;uname&#39;);
      
        //判断用户是否登录
        if(!$sess_auth){
            jumpTo(&#39;/login/index&#39;);
            exit;
            //检查到用户登录后, 还要检测该用户是否具有操作某个页面的权限, (是否具有操作某个方法的权限)
        }else{
            $auth = new Auth();
            if(!$auth->check(request()->controller().&#39;/&#39;.request()->action(),$sess_auth)){
                historyTo(&#39;抱歉~你没有操作该栏目的权限,请联系管理员!&#39;);
                exit;
            }
        }
    }
}

    lib\Auth;/**权限认证类**/
    

<?php
use think\facade\Db;
use think\facade\Config;
use think\facade\Session;
use think\facade\Request;



class Auth
{
    protected $_config = [
        &#39;auth_on&#39;           =>  true,                // 认证开关
        &#39;auth_type&#39;         =>  1,                   // 认证方式,1为实时认证;2为登录认证。
        &#39;auth_role&#39;        =>  &#39;auth_role&#39;,        // 用户组数据表名
        &#39;users_role&#39; =>   &#39;users_role&#39;, // 用户-用户组关系表
        &#39;auth_rule&#39;         =>  &#39;auth_rule&#39;,         // 权限规则表
        &#39;auth_user&#39;         =>  &#39;users&#39;,             // 用户信息表
        
    ];
    
    public function __construct()
    {
        if (Config::get(&#39;app.auth&#39;)) {
            $this->_config = array_merge($this->_config, Config::get(&#39;app.auth&#39;));
        }
    }
    
    /**
     * 检查权限
     * @param  string|array  $name     需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @param  integer  $uid      认证用户ID
     * @param  string   $relation 如果为 &#39;or&#39; 表示满足任一条规则即通过验证;如果为 &#39;and&#39; 则表示需满足所有规则才能通过验证
     * @param  string   $mode     执行check的模式
     * @param  integer  $type     规则类型
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check($name, $uid, $relation = &#39;or&#39;, $mode = &#39;url&#39;, $type = 1)
    {
        if (!$this->_config[&#39;auth_on&#39;]) {
            return true;
        }
        $authList = $this->getAuthList($uid, $type);
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, &#39;,&#39;) !== false) {
                $name = explode(&#39;,&#39;, $name);
            } else {
                $name = [$name];
            }
        }
        $list = [];
        if ($mode === &#39;url&#39;) {
            $REQUEST = unserialize(strtolower(serialize($_REQUEST)));
        }
        foreach ($authList as $auth) {

            $query = preg_replace(&#39;/^.+\?/U&#39;, &#39;&#39;, $auth);
            if ($mode === &#39;url&#39; && $query != $auth) {
                parse_str($query, $param); // 解析规则中的param
                $intersect = array_intersect_assoc($REQUEST, $param);
                $auth = preg_replace(&#39;/\?.*$/U&#39;, &#39;&#39;, $auth);
                if (in_array($auth, $name) && $intersect == $param) {
                    $list[] = $auth;
                }
            } elseif (in_array($auth, $name)) {
                $list[] = $auth;
            }
        }
        if ($relation === &#39;or&#39; && !empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ($relation === &#39;and&#39; && empty($diff)) {
            return true;
        }
        return false;
    }
    /**
     * 根据用户ID获取用户组,返回值为数组
     * @param  integer $uid 用户ID
     * @return array      用户所属用户组 [&#39;uid&#39;=>&#39;用户ID&#39;, &#39;group_id&#39;=>&#39;用户组ID&#39;, &#39;title&#39;=>&#39;用户组名&#39;, &#39;rules&#39;=>&#39;用户组拥有的规则ID,多个用英文,隔开&#39;]
     */
    public function getGroups($uid)
    {
        static $groups = [];
        if (isset($groups[$uid])) {
            return $groups[$uid];
        }
        $user_groups = Db::name($this->_config[&#39;users_role&#39;])
            ->alias(&#39;ur&#39;)
            ->where(&#39;ur.uid&#39;, $uid)
            ->where(&#39;ar.status&#39;, 1)
            ->join($this->_config[&#39;auth_role&#39;].&#39; ar&#39;, "ur.role_id = ar.id")
            ->field(&#39;uid,role_id,title,rules&#39;)
            ->select();
        $groups[$uid] = $user_groups ?: [];
        return $groups[$uid];
    }
    /**
     * 获得权限列表
     * @param  integer $uid  用户ID
     * @param  integer $type 规则类型
     * @return array       权限列表
     */
    protected function getAuthList($uid, $type)
    {
        static $_authList = [];
        $t = implode(&#39;,&#39;, (array)$type);
        if (isset($_authList[$uid.$t])) {
            return $_authList[$uid.$t];
        }
        if ($this->_config[&#39;auth_type&#39;] == 2 && Session::has(&#39;_AUTH_LIST_&#39;.$uid.$t)) {
            return Session::get(&#39;_AUTH_LIST_&#39;.$uid.$t);
        }
        // 读取用户所属用户组
        $groups = $this->getGroups($uid);
        $ids = []; // 保存用户所属用户组设置的所有权限规则ID
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(&#39;,&#39;, trim($g[&#39;rules&#39;], &#39;,&#39;)));
        }
        $ids = array_unique($ids);
        if (empty($ids)) {
            $_authList[$uid.$t] = [];
            return [];
        }
        $map = [
            [&#39;id&#39;, &#39;in&#39;, $ids],
            [&#39;type&#39;, &#39;=&#39;, $type],
            [&#39;status&#39;, &#39;=&#39;, 1]
        ];
        // 读取用户组所有权限规则
        $rules = Db::name($this->_config[&#39;auth_rule&#39;])->where($map)->field(&#39;condition,name&#39;)->select();
        // 循环规则,判断结果。
        $authList = [];
        foreach ($rules as $rule) {
            if (!empty($rule[&#39;condition&#39;])) { // 根据condition进行验证
                $user = $this->getUserInfo($uid); // 获取用户信息,一维数组
                $command = preg_replace(&#39;/\{(\w*?)\}/&#39;, &#39;$user[\&#39;\\1\&#39;]&#39;, $rule[&#39;condition&#39;]);
                // dump($command); // debug
                @(eval(&#39;$condition=(&#39;.$command.&#39;);&#39;));
                if ($condition) {
                    $authList[] = strtolower($rule[&#39;name&#39;]);
                }
            } else {
                // 只要存在就记录
                $authList[] = strtolower($rule[&#39;name&#39;]);
            }
        }
        $_authList[$uid.$t] = $authList;
        if ($this->_config[&#39;auth_type&#39;] == 2) {
            Session::set(&#39;_AUTH_LIST_&#39;.$uid.$t, $authList);
        }
        return array_unique($authList);
    }
    /**
     * 获得用户资料,根据自己的情况读取数据库
     */
    protected function getUserInfo($uid) {
        static $user_info = [];

        $user = Db::name($this->config[&#39;auth_user&#39;]);
        // 获取用户表主键
        $_pk = is_string($user->getPk()) ? $user->getPk() : &#39;uid&#39;;
        if (!isset($user_info[$uid])) {
            $user_info[$uid] = $user->where($_pk, $uid)->find();
        }

        return $user_info[$uid];
    }
}

    这样就能实现路由操作权限的实时检测,比如我们让首页控制器继承中间控制器:

<?php
namespace app\admin\controller;
use think\Request;
use think\facade\Db;//db类
use think\facade\Session;
use lib\Rule;
class Index extends Common
{
    public function index()
    { 
        $uname = session(&#39;uname&#39;);
        $uid = session(&#39;uid&#39;);
        // 根据uid,获取该用户相应的权限,连表查询
        $res = Db::name(&#39;users&#39;)->alias(&#39;u&#39;)->where(&#39;u.uid&#39;,$uid)
        ->leftJoin(&#39;users_role ur&#39;,&#39;ur.uid = u.uid&#39;)
        ->leftJoin(&#39;auth_role ar&#39;,&#39;ar.id = ur.role_id&#39;)
        ->field(&#39;u.uid,u.uname,ar.rules&#39;)
        ->select()->toArray();
        // dd($res);
        $rules = implode(",",array_column($res,&#39;rules&#39;));
        // dd( $rules);
        //in查询 根据获取到的rules id 选权限列表
        $res = Db::name(&#39;auth_rule&#39;)->field(&#39;id,name,title,pid&#39;)->order(&#39;id&#39;,&#39;asc&#39;)->where(&#39;is_menu&#39;,1)
        ->where(&#39;id&#39;,&#39;in&#39;,$rules)->select();
        // dump($res);
        //这里使用扩展类Rule中封装的无限极分类方法
        $rlist = Rule::Rulelayer($res);
        // dd($rlist);
        $data = [
            &#39;uid&#39;=>$uid,
            &#39;uname&#39;=>$uname,
            &#39;rlist&#39;=>$rlist,
            &#39;create_time&#39;=>1617252175
        ];
            return view(&#39;index&#39;, $data);
            
    }
 }

最终实现的效果如图:

RBAC permission control implementation principle - design of permission table, user table and association table


The above is the detailed content of RBAC permission control implementation principle - design of permission table, user table and association table. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn