thinkphp5 Auth 权限管理

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第31天,点击查看活动详情

入行接触的第一个框架就是thinkphp。那个时候还是3.2版本。现在已经升级到了6.1版本。

对比一下,3.2版本虽然功能不是特别完善,但是可扩展性强(就是怎么改都行)。

5.1版本虽然功能相对完善,但是可扩展性就差了许多。而且,取消了3.2版本的Auth权限管理。3.2版本的时候,尝试过这个功能,挺好用的。

博客后台是5.1版本写的,也想加入一下这个功能

我要说下边这个类是我自己写的,你也不能信,我也不能那么说……下边这个类是基于thinkphp3.2的auth管理类修改的。

网上相关的类还是挺多的,但是吧,也就那回事吧,这个是我的博客正在使用的类,亲测好用,感兴趣的,可以尝试下。

先说下存放位置

auth文件位置.png

使用auth需要建三张表,建表语句如下所示:

-- ----------------------------
 
  -- mt4_auth_rule,规则表,
 
  -- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证
 
  -- ----------------------------
 
  DROP TABLE IF EXISTS `auth_rule`;
 
  CREATE TABLE `auth_rule` (
 
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
 
  `name` char(80NOT NULL DEFAULT '',
 
  `title` char(20NOT NULL DEFAULT '',
 
  `type` tinyint(1NOT NULL DEFAULT '1',
 
  `status` tinyint(1NOT NULL DEFAULT '1',
 
  `conditionchar(100NOT NULL DEFAULT '',  # 规则附件条件,满足附加条件的规则,才认为是有效的规则
 
  PRIMARY KEY (`id`),
 
  UNIQUE KEY `name` (`name`)
 
  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
 
  -- ----------------------------
 
  -- mt4_auth_group 用户组表,
 
  -- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用
 
  -- ----------------------------
 
  DROP TABLE IF EXISTS `auth_group`;
 
  CREATE TABLE `auth_group` (
 
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
 
  `title` char(100NOT NULL DEFAULT '',
 
  `status` tinyint(1NOT NULL DEFAULT '1',
 
  `rules` char(80NOT NULL DEFAULT '',
 
  PRIMARY KEY (`id`)
 
  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
 
  -- ----------------------------
 
  -- auth_group_access 用户组明细表
 
  -- uid:用户id,group_id:用户组id
 
  -- ----------------------------
 
  DROP TABLE IF EXISTS `auth_group_access`;
 
  CREATE TABLE `auth_group_access` (
 
  `uid` mediumint(8) unsigned NOT NULL,
 
  `group_id` mediumint(8) unsigned NOT NULL,
 
  UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
 
  KEY `uid` (`uid`),
 
  KEY `group_id` (`group_id`)
 
  ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

权限管理类代码:

<?php
// +----------------------------------------------------------------------
 
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
 
// +----------------------------------------------------------------------
 
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
 
// +----------------------------------------------------------------------
 
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 
// +----------------------------------------------------------------------
 
// | Author: GC <[email protected]> 
 
// +----------------------------------------------------------------------
 
namespace org;
 
use thinkConfig;
 
use thinkSession;
 
use thinkDb;
 
/**
 
 * 权限认证类
 
 */
 
//数据库
 
class Auth {
 
    //默认配置
 
    protected $config array(
 
        'auth_on'           => true,                      // 认证开关
 
        'auth_type'         => 2,                         // 认证方式,1为实时认证;2为登录认证。
 
        'auth_group'        => 'auth_group',        // 用户组数据表名
 
        'auth_group_access' => 'auth_group_access'// 用户-用户组关系表
 
        'auth_rule'         => 'auth_rule',         // 权限规则表
 
        'auth_user'         => 'admin'             // 用户信息表
 
    );
 
   
 
    public function __construct({
 
        if (Config::get('auth_config')) {
 
            $this->config = array_merge($this->config, Config::get('auth_config')); //可设置配置项 auth_config, 此配置项为数组。
 
        }
 
    }
 
    /**
 
     * 检查权限
 
     * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 
     * @param uid  int           认证用户的id
 
     * @param string mode        执行check的模式
 
     * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 
     * return boolean           通过验证返回true;失败返回false
 
     */
 
    public function check($name$uid$type 1$mode 'url'$relation 'or'{
 
        if (!$this->config['auth_on']) {
 
            return true;
 
        }
 
        $authList $this->getAuthList($uid$type); //获取用户需要验证的所有有效规则列表
 
        if (is_string($name)) {
 
            $name = strtolower($name);
 
//            if (strpos($name, ',') !== false) {
 
//                $name = explode(',', $name);
 
//            } else {
 
//                $name = [$name];
 
//            }
 
            $name = strpos($name',') !== false ? explode(','$name) : [$name];
 
        }
 
        $list = []; //保存验证通过的规则名
 
        if ($mode == 'url') {
 
            $REQUEST = unserialize(strtolower(serialize($_REQUEST)));
 
        }
 
        foreach ($authList as $auth) {
 
            $query = preg_replace('/^.+?/U'''$auth);
 
            if ($mode == 'url' && $query != $auth) {
 
                parse_str($query$param); //解析规则中的param
 
                $intersect = array_intersect_assoc($REQUEST$param);
 
                $auth = preg_replace('/?.*$/U'''$auth);
 
                if (in_array($auth$name) && $intersect == $param) {  //如果节点相符且url参数满足
 
                    $list[] = $auth;
 
                }
 
            } else if (in_array($auth$name)) {
 
                $list[] = $auth;
 
            }
 
        }
 
        if ($relation == 'or' and ! empty($list)) {
 
            return false;
 
        }
 
        $diff = array_diff($name$list);
 
        if ($relation == 'and' and empty($diff)) {
 
            return false;
 
        }
 
        return true;
 
    }
 
    /**
 
     * 根据用户id获取用户组,返回值为数组
 
     * @param  uid int     用户id
 
     * return array       用户所属的用户组 [
 
     *     ['uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
 
     *     ...)  
 
     */
 
    public function getGroups($uid{
 
        static $groups = [];
 
        if (isset($groups[$uid])) {
 
            return $groups[$uid];
 
        }
 
        $user_groups = Db::view($this->config['auth_group_access'], 'uid,group_id')->view($this->config['auth_group'], 'title,rules'"{$this->config['auth_group_access']}.group_id={$this->config['auth_group']}.id")
 
                        ->where(['uid' => $uid'status' => 1])->select();
 
        $groups[$uid] = $user_groups $user_groups : [];
 
        return $groups[$uid];
 
    }
 
    /**
 
     * 获得权限列表
 
     * @param integer $uid  用户id
 
     * @param integer $type
 
     */
 
    protected function getAuthList($uid$type{
 
        static $_authList = []; //保存用户验证通过的权限列表
 
        $t = implode(',', (array$type);
 
        if (isset($_authList[$uid $t])) {
 
            return $_authList[$uid $t];
 
        }
 
        if ($this->config['auth_type'] == 2 && Session::has('_auth_list_' . $uid $t)) {
 
            return Session::get('_auth_list_' . $uid $t);
 
        }
 
        //读取用户所属用户组
 
        $groups $this->getGroups($uid);
 
        $ids = []; //保存用户所属用户组设置的所有权限规则id
 
        foreach ($groups as $g) {
 
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
 
        }
 
        $ids = array_unique($ids);
 
        if (empty($ids)) {
 
            $_authList[$uid $t] = [];
 
            return [];
 
        }
 
        $map = [
 
            'id' => ['notin'$ids],
 
            'type' => $type,
 
            'status' => 1,
 
        ];
 
        //读取用户组所有权限规则
 
        $rules = Db::name($this->config['auth_rule'])->where($map)->field('condition,name')->select();
 
        //循环规则,判断结果。
 
        $authList = [];   //
 
        foreach ($rules as $rule) {
 
            if (!empty($rule['condition'])) { //根据condition进行验证
 
                $this->getUserInfo($uid); //获取用户信息,一维数组
 
                $command = preg_replace('/{(w*?)}/''$user['1']'$rule['condition']);
 
                @(eval('$condition=(' . $command ');'));
 
                $condition && $authList[] = strtolower($rule['name']);
 
            } else {
 
                $authList[] = strtolower($rule['name']); //只要存在就记录
 
            }
 
        }
 
        $_authList[$uid $t] = $authList;
 
        if ($this->config['auth_type'] == 2) {
 
            $_SESSION['_auth_list_' . $uid $t] = $authList//规则列表结果保存到session
 
        }
 
        return array_unique($authList);
 
    }
 
    /**
 
     * 获得用户资料,根据自己的情况读取数据库
 
     */
 
    protected function getUserInfo($uid{
 
        static $userinfo = [];
 
        if (!isset($userinfo[$uid])) {
 
            $userinfo[$uid] = Db::name($this->config['auth_user'])->where(['id' => $uid])->find();
 
        }
 
        return $userinfo[$uid];
 
    }
 
}

下边是调用方法:

<?php
namespace appadmincontroller;
use appadminmodelWaterModel;
use thinkController;
use thinkRequest;//使用request对象
use thinkDb;//引入数据库操作类
use thinkSession;//使用session驱动
use thinkLoader;
 
class Base extends Controller
{
    public function __construct()
    {
        $auth new orgAuth();
        $au $auth->check(request()->module().'/'.request()->controller().'/'.request()->action(), $session['id']);
        if (!$au) {// 第一个参数是规则名称,第二个参数是用户UID
            $result['login_code'] = -2;
            $result['login_msg'] = "没有权限";
            echo json_encode($result);die;
        }
    }
}

这些代码按照正确的方式,放到你的项目中,auth权限管理应该就好用了。如果你的项目支持中间件,上边这部分代码直接放到中间件中就可以了。

我就是这样。

有好的建议,请在下方输入你的评论

欢迎访问个人博客:guanchao.site

欢迎访问我的小程序:打开微信->发现->小程序->搜索“时间里的”

猜你喜欢

转载自juejin.im/post/7112597683088392222