search
HomeBackend DevelopmentPHP TutorialTP5 Auth permission management example

TP5 Auth permission management example

Dec 27, 2017 pm 06:04 PM
authExamplePermissions

权限管理是一个项目中必不可少的模块之一,常用的有RBAC、Auth等。本文就分享在TP5中通过Auth验证权限的实例,希望对大家有所帮助。

<?php
namespace think;
use think\Config;
use think\Session;
use think\Db;
/**
 * 权限认证类
 */
//数据库
/*
  -- ----------------------------
  -- mt4_auth_rule,规则表,
  -- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证
  -- ----------------------------
  DROP TABLE IF EXISTS `mt4_auth_rule`;
  CREATE TABLE `mt4_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;
  -- ----------------------------
  -- mt4_auth_group 用户组表,
  -- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用
  -- ----------------------------
  DROP TABLE IF EXISTS `mt4_auth_group`;
  CREATE TABLE `mt4_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;
  -- ----------------------------
  -- mt4_auth_group_access 用户组明细表
  -- uid:用户id,group_id:用户组id
  -- ----------------------------
  DROP TABLE IF EXISTS `mt4_auth_group_access`;
  CREATE TABLE `mt4_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;
 */

class Auth {
    //默认配置
    protected $config = array(
        &#39;auth_on&#39;           => true,                      // 认证开关
        &#39;auth_type&#39;         => 2,                         // 认证方式,1为实时认证;2为登录认证。
        &#39;auth_group&#39;        => &#39;auth_group&#39;,        // 用户组数据表名
        &#39;auth_group_access&#39; => &#39;auth_group_access&#39;, // 用户-用户组关系表
        &#39;auth_rule&#39;         => &#39;auth_rule&#39;,         // 权限规则表
        &#39;auth_user&#39;         => &#39;auth_admin&#39;             // 用户信息表
    );
    
    public function __construct() {
        if (Config::get(&#39;auth_config&#39;)) {
            $this->config = array_merge($this->config, Config::get(&#39;auth_config&#39;)); //可设置配置项 auth_config, 此配置项为数组。
        }
    }
    /**
     * 检查权限
     * @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 = [$name];
//            }
            $name = strpos($name, &#39;,&#39;) !== false ? explode(&#39;,&#39;, $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) {  //如果节点相符且url参数满足
                    $list[] = $auth;
                }
            } else if (in_array($auth, $name)) {
                $list[] = $auth;
            }
        }
        if ($relation == &#39;or&#39; and ! empty($list)) {
            return false;
        }
        $diff = array_diff($name, $list);
        if ($relation == &#39;and&#39; and empty($diff)) {
            return false;
        }
        return true;
    }
    /**
     * 根据用户id获取用户组,返回值为数组
     * @param  uid int     用户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::view($this->config[&#39;auth_group_access&#39;], &#39;uid,group_id&#39;)->view($this->config[&#39;auth_group&#39;], &#39;title,rules&#39;, "{$this->config[&#39;auth_group_access&#39;]}.group_id={$this->config[&#39;auth_group&#39;]}.id")
                        ->where([&#39;uid&#39; => $uid, &#39;status&#39; => 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(&#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;notin&#39;, $ids],
            &#39;type&#39; => $type,
            &#39;status&#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进行验证
                $this->getUserInfo($uid); //获取用户信息,一维数组
                $command = preg_replace(&#39;/\{(\w*?)\}/&#39;, &#39;$user[\&#39;\\1\&#39;]&#39;, $rule[&#39;condition&#39;]);
                @(eval(&#39;$condition=(&#39; . $command . &#39;);&#39;));
                $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[&#39;_auth_list_&#39; . $uid . $t] = $authList; //规则列表结果保存到session
        }
        return array_unique($authList);
    }
    /**
     * 获得用户资料,根据自己的情况读取数据库
     */
    protected function getUserInfo($uid) {
        static $userinfo = [];
        if (!isset($userinfo[$uid])) {
            $userinfo[$uid] = Db::name($this->config[&#39;auth_user&#39;])->where([&#39;uid&#39; => $uid])->find();
        }
        return $userinfo[$uid];
    }
}

相关推荐:

PHP实现权限管理功能的方法

ThinkPHP(RBAC)权限管理视频以及资料(源码、课件)分享

php实例-php 人员权限管理(RBAC)实例(推荐)

The above is the detailed content of TP5 Auth permission management example. 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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!