On the analysis of THINKPHP5 framework AUTH permission control class and usage

Source: Internet
Author: User
This article mainly introduces the THINKPHP5 framework Auth permission control class and usage, and analyzes the definition and use method of THINKPHP5 Framework extended AUTH permission control class with the example form, the code comments are provided with more detailed instructions and database operation statements, the need for friends can refer to the following

This paper describes the THINKPHP5 framework Auth permission control class. Share to everyone for your reference, as follows:

This is a relatively simple usage:

Directly put out the class, here I changed, I did not use UID, because I built the table is the admin table, so the corresponding query in the code to change the aid

and the name of the table, I've removed the prefix.

<?php//+----------------------------------------------------------------------//| thinkphp [WE CAN do it JUST THINK it]//+----------------------------------------------------------------------//| Copyright (c) http://thinkphp.cn All rights reserved.//+------------------------------------------------------- ---------------// | Licensed (http://www.apache.org/licenses/LICENSE-2.0)//+------------------------------------------------------- ---------------// | author:luofei614 <weibo.com/luofei614>//+---------------------------------------------------------------- ------Namespace auth;/** * Permission Authentication class * Features: * 1, is the rule certification, not to the node authentication. The user can authenticate the node as a rule name implementation. * $auth =new auth (); $auth->check (' rule name ', ' User ID ') * 2, you can certify multiple rules at the same time and set the relationship of multiple rules (or OR and) * $auth =new auth (); $auth->check (' rule 1, Rule 2 ', ' User ID ', ' and ') * When the third parameter is and, the user needs to have both rule 1 and Rule 2 permissions. When the third argument is or, the user value needs to have one of these conditions. By default, or * 3, a user can belong to more than one user group (the Think_auth_group_access table defines the user group to which users belong). We need to set what rules each user group has (Think_auth_group defines the user group rightsLimit) * * 4, support for regular expressions. * When a rule is defined in the Think_auth_rule table, the Condition field can define a rule expression if the type is 1. This rule does not pass if the definition {score}>5 and {score}<100 indicates that the user's score is between 5-100. *///Database/*--------------------------------think_auth_rule, Rule table,--ID: Primary key, Name: rule uniquely identifies (is a common routing list, such as: Admin/index/index ), title: The Chinese name of the rule, such as Add Item status state: 1 Normal, 0 disabled, condition: Regular expression, NULL indicates existence on validation, non-null means validation by condition------------------------------ DROP TABLE IF EXISTS ' auth_rule '; CREATE TABLE ' auth_rule ' (' ID ' mediumint (8) unsigned not NULL auto_increment, ' name ' char (a) NOT null DEFAULT ' ', ' ti Tle ' char ' is not null default ' ', ' type ' tinyint (1) is not null default ' 1 ', ' status ' tinyint (1) is not null default ' 1 ', ' C Ondition ' char (+) not NULL DEFAULT ' ', # Rule attachment condition, rules that satisfy additional conditions are considered valid rules PRIMARY key (' id '), UNIQUE key ' name ' (' name ') EN Gine=myisam DEFAULT Charset=utf8;--------------------------------auth_group User Group table,--ID: Primary KEY, Title: User Group Chinese name, Rules: User groups have rule IDs, multiple rules "," separated, status state: 1 normal, 0 disabled------------------------------DROP TABLE IF EXISTS ' Auth_group '; CREATE TABLE ' Auth_group ' (' ID ' mediumint (8) unsigned not NULL auto_increment, ' title ' char (+) ' NOT null DEFAULT ' ', ' status ' tin Yint (1) NOT null default ' 1 ', ' rules ' char (+) NOT null default ', PRIMARY KEY (' id ')) engine=myisam default Charset=ut F8;--------------------------------group_access User Group Schedule-UID: User id,group_id: User group 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 K EY ' uid_group_id ' (' uid ', ' group_id '), key ' uid ' (' uid '), key ' group_id ' (' group_id ')) Engine=myisam DEFAULT Charset=utf8 ; */class auth{//default configuration protected $_config = Array (' auth_on ' = true,//authentication switch ' auth_type ' =&gt ;    1,///authentication method, 1 for real-time authentication, 2 for login authentication.      ' Auth_group ' = ' auth_group ',//user group data table name ' auth_group_access ' = ' group_access ',//user-user Group Relationship table ' Auth_rule '     = ' auth_rule ',//Permission rules table ' auth_user ' + ' admin '  User Information table);      Public Function __construct () {if (config (' auth_config ')) {//can set the configuration item auth_config, this configuration item is an array.    $this->_config = Array_merge ($this->_config, config (' auth_config ')); }}/** * Check permissions * @param name String|array A list of rules that need to be validated, support for comma-delimited permission rules or indexed arrays * @param UID int authenticated User ID * @param stri      Ng mode performs a check pattern * @param relation string If either of the rules is validated by ' or ', or if ' and ' means that all rules need to be met to pass validation * @return Boolean The validation returns true; the failure returns false */Public function check ($name, $uid, $type =1, $mode = ' url ', $relation = ' or ') {if (! $this-&gt    ; _config[' auth_on ') return true; $authList = $this->getauthlist ($uid, $type);      Gets the list of all valid rules that the user needs to validate if (is_string ($name)) {$name = Strtolower ($name);      if (Strpos ($name, ', ')!== false) {$name = explode (', ', $name);      } else {$name = array ($name); }} $list = Array ();    Save validation through the rule name 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 in parse rule $intersect = Array_int        Ersect_assoc ($REQUEST, $param); $auth = Preg_replace ('/\?.        *$/u ', ', $auth);        if (In_array ($auth, $name) && $intersect = = $param) {//If the node matches and the URL parameter satisfies $list [] = $auth;      }}else if (In_array ($auth, $name)) {$list [] = $auth;    }} if ($relation = = ' or ' and!empty ($list)) {return true;    } $diff = Array_diff ($name, $list);    if ($relation = = ' and ' and Empty ($diff)) {return true;  } return false; /** * Gets the user group based on the user ID, the return value is an array of * @param UID int User ID * @return Array user belongs to the user group array (' uid ' = ' User ID ',   ' group_id ' + ' user group ID ', ' title ' = ' user group name ', ' rules ' + ' user group has rule ID, multiple, number separated '), * ...)    */Public Function getgroups ($uid) {Static $groups = array (); if (Isset ($groups [$uid])) return $groups[$uid]; $user _groups = \think\db::name ($this->_config[' auth_group_access ')->alias (' A ')->join ($this->_conf ig[' Auth_group ']. "G", "g.id=a.group_id")->where ("A.aid= ' $uid ' and g.status= ' 1 '")->field (' Aid,group_id,t    Itle,rules ')->select (); $groups [$uid] = $user _groups?    $user _groups:array ();  return $groups [$uid];     /** * Get permission list * @param integer $uid User ID * @param integer $type */protected function getauthlist ($uid, $type) { Static $_authlist = Array ();    Save user authentication through the list of permissions $t = Implode (', ', (array) $type);    if (Isset ($_authlist[$uid. $t]) {return $_authlist[$uid. $t]; } if ($this->_config[' auth_type ']==2 && isset ($_session[' _auth_list_ '. $uid. $t]) {return $_session[' _au    Th_list_ '. $uid. $t];    }//Read user group $groups = $this->getgroups ($uid); $ids = Array ();//Save all permission rule IDs for user groups set by users foreach ($groups as $g) {$ids = Array_merge ($ids, Explode (', ', Trim ($g [' Rul    Es '], ', ')); } $ids = Array_unique ($ids);      if (empty ($ids)) {$_authlist[$uid. $t] = array ();    return Array ();    } $map =array (' id ' =>array (' in ', $ids), ' type ' = = $type, ' status ' =>1,); Read user group all permission rules $rules = \think\db::name ($this->_config[' Auth_rule ')->where ($map)->field (' Condition,name ')    )->select ();    Cyclic rules, judging the results.  $authList = Array (); foreach ($rules as $rule) {if (!empty ($rule [' condition '))} {//condition verified $user = $this->getuse Rinfo ($UID);//Get user information, one-dimensional array $command = Preg_replace ('/\{(\w*?)        \}/', ' $user [\ ' \\1\ '] ', $rule [' condition ']); Dump ($command)//debug @ (eval (' $condition = ('. $command.        ');'));        if ($condition) {$authList [] = Strtolower ($rule [' name ']);      }} else {//record $authList as long as it exists [] = Strtolower ($rule [' name ']);    }} $_authlist[$uid. $t] = $authList; if ($this->_config[' Auth_type ']==2) {//Rule list results saved to SESSION $_session[' _auth_list_ '. $uid. $t]= $authList;  } return Array_unique ($authList);    }/** * Obtain user information, read the database according to your own situation */protected function GetUserInfo ($uid) {static $userinfo =array (); if (!isset ($userinfo [$uid])) {$userinfo [$uid]=\think\db::name ($this->_config[' Auth_User '])->where (Array ('    Aid ' = $uid)]->find ();  } return $userinfo [$uid]; }}

The auth.php is placed in the Auth directory below extend , and the namespace is Auth

You then use the constructor in the controller you are using, or you inherit a controller that uses the constructor method, which is constructed as follows:

Public Function _initialize () {    $aid = 1;    $auth = new \auth\auth ();    $request = Request::instance ();    $au = $auth->check ($request->module (). '/' . $request->controller (). '/' . $request->action (), $aid);    if (! $au) {//The first parameter is the rule name, the second parameter is the user UID      /* return array (' status ' = ' error ', ' msg ' = ' + ' has permission!). *      /$this->error (' You have no permissions ');}    }

The above $aid should be obtained after the user logs in, the user ID should normally be session() obtained

Related business logic can be self-judged, the rest is to add the county, user groups add Ah, and so on series additions and deletions to check.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.