search
HomeBackend DevelopmentPHP TutorialAnalysis of thinkPHP5 framework auth permission control classes and usage

这篇文章主要介绍了thinkPHP5框架auth权限控制类与用法,结合实例形式分析了thinkPHP5框架扩展auth权限控制类的定义与使用方法,代码注释中备有较为详尽的使用说明与数据库操作语句,需要的朋友可以参考下

本文实例讲述了thinkPHP5框架auth权限控制类。分享给大家供大家参考,具体如下:

这个是比较简单的用法:

直接把类贴出来,这里我改了,我没有用uid,因为我建的表是admin表,所以代码里对应查询改成了aid

还有表名,我都去掉了前缀

<?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: luofei614 <weibo.com/luofei614> 
// +----------------------------------------------------------------------
namespace auth;
/**
 * 权限认证类
 * 功能特性:
 * 1,是对规则进行认证,不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
 *   $auth=new Auth(); $auth->check(&#39;规则名称&#39;,&#39;用户id&#39;)
 * 2,可以同时对多条规则进行认证,并设置多条规则的关系(or或者and)
 *   $auth=new Auth(); $auth->check(&#39;规则1,规则2&#39;,&#39;用户id&#39;,&#39;and&#39;)
 *   第三个参数为and时表示,用户需要同时具有规则1和规则2的权限。 当第三个参数为or时,表示用户值需要具备其中一个条件即可。默认为or
 * 3,一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
 *
 * 4,支持规则表达式。
 *   在think_auth_rule 表中定义一条规则时,如果type为1, condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100 表示用户的分数在5-100之间时这条规则才会通过。
 */
//数据库
/*
-- ----------------------------
-- think_auth_rule,规则表,
-- id:主键,name:规则唯一标识(就是常见的路由列表,如:admin/index/index), 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(80) NOT NULL DEFAULT &#39;&#39;,
  `title` char(20) NOT NULL DEFAULT &#39;&#39;,
  `type` tinyint(1) NOT NULL DEFAULT &#39;1&#39;,
  `status` tinyint(1) NOT NULL DEFAULT &#39;1&#39;,
  `condition` char(100) NOT NULL DEFAULT &#39;&#39;, # 规则附件条件,满足附加条件的规则,才认为是有效的规则
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- 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(100) NOT NULL DEFAULT &#39;&#39;,
  `status` tinyint(1) NOT NULL DEFAULT &#39;1&#39;,
  `rules` char(80) NOT NULL DEFAULT &#39;&#39;,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- group_access 用户组明细表
-- uid:用户id,group_id:用户组id
-- ----------------------------
DROP TABLE IF EXISTS `group_access`;
CREATE TABLE `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;
 */
class Auth{
  //默认配置
  protected $_config = array(
    &#39;auth_on&#39;      => true,           // 认证开关
    &#39;auth_type&#39;     => 1,             // 认证方式,1为实时认证;2为登录认证。
    &#39;auth_group&#39;    => &#39;auth_group&#39;,    // 用户组数据表名
    &#39;auth_group_access&#39; => &#39;group_access&#39;, // 用户-用户组关系表
    &#39;auth_rule&#39;     => &#39;auth_rule&#39;,     // 权限规则表
    &#39;auth_user&#39;     => &#39;admin&#39;       // 用户信息表
  );
  public function __construct() {
    if (config(&#39;auth_config&#39;)) {
      //可设置配置项 auth_config, 此配置项为数组。
      $this->_config = array_merge($this->_config, config(&#39;auth_config&#39;));
    }
  }
  /**
   * 检查权限
   * @param name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
   * @param uid int      认证用户的id
   * @param string mode    执行check的模式
   * @param relation string  如果为 &#39;or&#39; 表示满足任一条规则即通过验证;如果为 &#39;and&#39;则表示需满足所有规则才能通过验证
   * @return boolean      通过验证返回true;失败返回false
   */
  public function check($name, $uid, $type=1, $mode=&#39;url&#39;, $relation=&#39;or&#39;) {
    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 = array($name);
      }
    }
    $list = array(); //保存验证通过的规则名
    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 ) { //如果节点相符且url参数满足
          $list[] = $auth ;
        }
      }else if (in_array($auth , $name)){
        $list[] = $auth ;
      }
    }
    if ($relation == &#39;or&#39; and !empty($list)) {
      return true;
    }
    $diff = array_diff($name, $list);
    if ($relation == &#39;and&#39; and empty($diff)) {
      return true;
    }
    return false;
  }
  /**
   * 根据用户id获取用户组,返回值为数组
   * @param uid int   用户id
   * @return array    用户所属的用户组 array(
   *   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 = array();
    if (isset($groups[$uid]))
      return $groups[$uid];
    $user_groups = \think\Db::name($this->_config[&#39;auth_group_access&#39;])
      ->alias(&#39;a&#39;)
      ->join($this->_config[&#39;auth_group&#39;]." g", "g.id=a.group_id")
      ->where("a.aid=&#39;$uid&#39; and g.status=&#39;1&#39;")
      ->field(&#39;aid,group_id,title,rules&#39;)->select();
    $groups[$uid] = $user_groups ? $user_groups : array();
    return $groups[$uid];
  }
  /**
   * 获得权限列表
   * @param integer $uid 用户id
   * @param integer $type
   */
  protected function getAuthList($uid,$type) {
    static $_authList = array(); //保存用户验证通过的权限列表
    $t = implode(&#39;,&#39;,(array)$type);
    if (isset($_authList[$uid.$t])) {
      return $_authList[$uid.$t];
    }
    if( $this->_config[&#39;auth_type&#39;]==2 && isset($_SESSION[&#39;_auth_list_&#39;.$uid.$t])){
      return $_SESSION[&#39;_auth_list_&#39;.$uid.$t];
    }
    //读取用户所属用户组
    $groups = $this->getGroups($uid);
    $ids = array();//保存用户所属用户组设置的所有权限规则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] = array();
      return array();
    }
    $map=array(
      &#39;id&#39;=>array(&#39;in&#39;,$ids),
      &#39;type&#39;=>$type,
      &#39;status&#39;=>1,
    );
    //读取用户组所有权限规则
    $rules = \think\Db::name($this->_config[&#39;auth_rule&#39;])->where($map)->field(&#39;condition,name&#39;)->select();
    //循环规则,判断结果。
    $authList = array();  //
    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
      $_SESSION[&#39;_auth_list_&#39;.$uid.$t]=$authList;
    }
    return array_unique($authList);
  }
  /**
   * 获得用户资料,根据自己的情况读取数据库
   */
  protected function getUserInfo($uid) {
    static $userinfo=array();
    if(!isset($userinfo[$uid])){
       $userinfo[$uid]=\think\Db::name($this->_config[&#39;auth_user&#39;])->where(array(&#39;aid&#39;=>$uid))->find();
    }
    return $userinfo[$uid];
  }
}

Auth.php放在extend下面的auth目录里,命名空间为auth

然后在使用的控制器中使用构造方法,或者继承一个使用了构造方法的控制器,构造方法如下:

public function _initialize()
{
    $aid = 1;
    $auth = new \auth\Auth();
    $request = Request::instance();
    $au = $auth->check($request->module() . &#39;/&#39; . $request->controller() . &#39;/&#39; . $request->action(), $aid);
    if (!$au) {// 第一个参数是规则名称,第二个参数是用户UID
      /* return array(&#39;status&#39;=>&#39;error&#39;,&#39;msg&#39;=>&#39;有权限!&#39;);*/
      $this->error(&#39;你没有权限&#39;);
    }
}

上面的$aid应该是用户登录以后获取的,正常情况下应该是session()获取的用户id

相关业务逻辑可以自行判断,剩下的就是添加全县,用户组添加啊,等等系列增删改查了。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

利用thinkPHP5框架实现基于ajax的分页功能解析

thinkPHP5框架中widget的功能与用法解析

Thinkphp和Bootstrap结合打造个性分页的样式

The above is the detailed content of Analysis of thinkPHP5 framework auth permission control classes and usage. 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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.