thinkphp Authority Authentication Auth example, thinkphpauth_php tutorial

Source: Internet
Author: User

thinkphp Authority Authentication Auth example, Thinkphpauth


This paper, in the form of instance code, deeply analyzes the realization principle and method of thinkphp authorization authentication auth, and the concrete steps are as follows:

MySQL database part SQL code:

--------------------------------table structure for think_auth_group------------------------------DROP table IF EXISTS ' Think_auth_group '; CREATE TABLE ' Think_auth_group ' (' ID ' mediumint (8) unsigned not NULL auto_increment, ' title ' char (+) ' NOT null DEFAULT ' ', ' status ' tinyint (1) NOT null default ' 1 ', ' rules ' char (+) NOT null default ' ', PRIMARY KEY (' id ')) Engine=myisam auto_ increment=2 DEFAULT Charset=utf8 comment= ' user groups table ';--------------------------------Records of Think_auth_group-------- ----------------------INSERT into ' think_auth_group ' VALUES (' 1 ', ' Management Group ', ' 1 ', ' + ');-------------------------------- Table structure for think_auth_group_access------------------------------DROP table IF EXISTS ' Think_auth_group_ Access '; CREATE TABLE ' think_auth_group_access ' (' UID ' mediumint (8) unsigned not NULL COMMENT ' user ID ', ' group_id ' Mediumint (8) Unsi gned not NULL COMMENT ' user group ID ', UNIQUE key ' uid_group_id ' (' uid ', ' group_id '), key ' uid ' (' uid '), key ' group_id ' (' group_id ') )) Engine=myiSAM DEFAULT Charset=utf8 comment= ' user group Schedule ';--------------------------------Records of think_auth_group_access------- -----------------------insert INTO ' think_auth_group_access ' VALUES (' 1 ', ' 1 '); insert INTO ' think_auth_group_access ' VALUES (' 1 ', ' 2 ');--------------------------------Table structure for think_auth_rule------------------------------ DROP TABLE IF EXISTS ' think_auth_rule '; CREATE TABLE ' think_auth_rule ' (' ID ' mediumint (8) unsigned not NULL auto_increment, ' name ' char (a) NOT null DEFAULT ' C ' Omment ' rule uniquely identifies ', ' title ' char (NOT null default ' COMMENT ' rule Chinese name ', ' status ' tinyint (1) NOT null default ' 1 ' COMMENT ' Status: 1 Normal, 0 disabled ', ' type ' char (a) NOT NULL, ' condition ' char (+) NOT null DEFAULT ' ' COMMENT ' regular expression, NULL indicates existence on validation, not NULL to validate by condition ', PRIMARY key (' id '), UNIQUE key ' name ' (' name ')) Engine=myisam auto_increment=5 DEFAULT charset=utf8 comment= ' rules table ';------- -------------------------Records of Think_auth_rule------------------------------INSERT into ' think_auth_rule ' VALUES(' 1 ', ' home/index ', ' list ', ' 1 ', ' home ', '); INSERT into ' Think_auth_rule ' VALUES (' 2 ', ' Home/add ', ' Add ', ' 1 ', ' home ', '); I Nsert into ' think_auth_rule ' values (' 3 ', ' Home/edit ', ' edit ', ' 1 ', ' Home ', '); INSERT into ' think_auth_rule ' values (' 4 ', ' Home/delete ', ' delete ', ' 1 ', ' Home ', ';D rop TABLE IF EXISTS ' Think_user '; CREATE TABLE ' Think_user ' (' id ' int (one) not NULL, ' username ' varchar () default NULL, ' password ' varchar (+) Default NUL L, ' age ' tinyint (2) default NULL, PRIMARY KEY (' id ')) engine=innodb default Charset=utf8;------------------------------- -Records of Think_user------------------------------INSERT into ' think_user ' VALUES (' 1 ', ' admin ', ' 21232f297a57a5a743894a0e4a801fc3 ', ' 25 ');

Configuration file application\common\conf\config.php section:

<?phpreturn Array (  //' config item ' = = ' config value '  db_dsn ' + ',//database connection DSN for PDO mode  ' db_type ' = ' mysql ',// Database type  ' db_host ' = ' localhost ',//server address  ' db_name ' = ' thinkphp ',//database name  ' Db_user ' + ' root ',//username  ' db_pwd ' + ' root ',//password  ' db_port ' + 3306,//Port  ' db_prefix ' = ' think_ ',//database table prefix     ' auth_conf IG ' = = Array (    ' auth_on ' = ' = ' = ' = '/'    auth_type ' + 1,//authentication mode, 1 for always-on authentication, 2 for login authentication.    ' auth_group ' = ' think_auth_group ',//user group data table name    ' auth_group_access ' = ' think_auth_group_access ',// User group Schedule ' auth_rule ' + '    think_auth_rule ',//Permission rules table    ' auth_user ' + ' think_user '//user information table)  ;

Project Home Controller Section application\home\controller\indexcontroller.class.php code:

<?phpnamespace home\controller;use Think\controller;class Indexcontroller extends Controller {public  function Index () {    $Auth = new \think\auth ();    A list of rules that need to be validated, support for comma-delimited permission rules or indexed arrays    $name = module_name. '/' . Action_name;    Current User id    $uid = ' 1 ';    Classification    $type = module_name;    The mode to perform the check    $mode = ' url ';    ' or ' means that any rule satisfies the validation;    ' and ' means that all rules must be met to validate    $relation = ' and ';    if ($Auth->check ($name, $uid, $type, $mode, $relation)) {die      (' Authentication: Success ');    } else {die      (' Authentication: Failed ');    }  }}

The above code is the most basic example of validation code.

Here is the source reading:

1. Permission Check class initialization configuration information:

$Auth = new \think\auth ();

When you create an object, the program merges the configuration information
The program merges the Auth_config array in the application\common\conf\config.php

  Public Function __construct () {    $prefix = C (' Db_prefix ');    $this->_config[' auth_group ') = $prefix. $this->_config[' Auth_group '];    $this->_config[' auth_rule ') = $prefix. $this->_config[' Auth_rule '];    $this->_config[' auth_user ') = $prefix. $this->_config[' Auth_User '];    $this->_config[' auth_group_access ') = $prefix. $this->_config[' auth_group_access '];    if (C (' Auth_config ')) {      //can be set to configuration item auth_config, this configuration item is an array.      $this->_config = Array_merge ($this->_config, C (' auth_config '));    }  }

2. Check Permissions:

Check ($name, $uid, $type = 1, $mode = ' url ', $relation = ' or ')

A rough analysis of this method

First determine whether to turn off the permission check if the configuration information Auth_on=>false does not perform permission validation or continue to verify permissions

if (! $this->_config[' auth_on ') {  return true;}

Getting a list of permissions is described in more detail:

$authList = $this->getauthlist ($uid, $type);

This time the list of rules to validate is converted to an array:

if (is_string ($name)) {  $name = Strtolower ($name);  if (Strpos ($name, ', ')!== false) {$name = explode (', ', $name);  } else {$name = array ($name);}  }

So the $name parameter is case-insensitive and will eventually be converted to lowercase


When you turn on URL mode, convert all to lowercase:

if ($mode = = ' url ') {  $REQUEST = unserialize (Strtolower (Serialize ($_request)));}

A permission check is one of the core code snippets, that is, looping all of the user rights to determine whether the permissions currently needed to be verified are in the user authorization list:

foreach ($authList as $auth) {  $query = preg_replace ('/^.+\?/u ', ' ", $auth);//Gets the URL parameter  if ($mode = = ' URL ' && ; $query! = $auth) {parse_str ($query, $param);//get array form URL parameter $intersect = ARRAY_INTERSECT_ASSOC ($REQUEST, $param); $auth = Preg_replace ('/\?.  *$/u ', ', $auth);//get access to the URL file 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;  }}

In_array ($auth, $name) If one of the permissions in the permission list equals the right that currently needs to be validated, add to $list
Note:

$list = Array (); Save validation Pass rule name if ($relation = = ' or ' and!empty ($list)) {  return true;} $diff = Array_diff ($name, $list), if ($relation = = ' and ' and Empty ($diff)) {  return true;} $relation = = ' or ' and!empty ($list); When or when one is passed, the permission is true $relation = = ' and ' and Empty ($diff); Permissions are true when and $name exactly equal to $list

3. Get permission list:

$authList = $this->getauthlist ($uid, $type); Get a list of all valid rules that users need to validate

This main process:

Get user groups

$groups = $this->getgroups ($uid);//select ' Rules ' from think_auth_group_access a INNER joins Think_auth_group G on A.gro Up_id=g.id WHERE (a.uid= ' 1 ' and g.status= ' 1 ')

The simplified operation is:

SELECT ' rules ' from think_auth_group where STATUS = ' 1 ' and id= ' 1 '///in the normal process to go to the think_auth_group_access table is a bit superfluous ...!!

Get user group Rules rule field This field is stored in the ID of the Think_auth_rule rule table, split

$ids is the ID array that the $groups variable is ultimately converted to:

$map = Array ('  id ' = = Array (' in ', $ids),  ' type ' = = $type,  ' status ' = 1,);

Obtain the rule information from the Think_auth_rule table, followed by the loop:

foreach ($rules as $rule) {   if (!empty ($rule [' condition '))} {//condition verified    $user = $this->getuserinfo ($ 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 ']);   }  } if (!empty ($rule [' condition '])) {//verify according to condition

Here you can understand that GetUserInfo will go to get the configuration file auth_user the corresponding table name to find the user information

The point is:

$command = Preg_replace ('/\{(\w*?) \}/', ' $user [\ ' \\1\ '] ', $rule [' condition ']); @ (eval (' $condition = ('. $command. ');'));

'/\{(\w*?) \}/can be considered to match the literal {string} then {string} will be replaced with $user[' string ')
$command = $user [' String ']

If

$rule [' condition '] = ' {age} ', $command = $user [' Age '] $rule [' condition '] = ' {age} > 5 ', $command = $user [' age '] > 10@ ( Eval (' $condition = ('. $command. ');'));

That

$condition = ($user [' age '] > 10);

Then look at the following code if True then add to the authorization list

if ($condition) {   $authList [] = Strtolower ($rule [' name ']);}

Thinkphp How to control personnel rights after landing

That's when you register. There is a select administrator, a field for the general administrator. And then log in to see if it's super admin.

thinkphp: How to display different content according to different permissions?

First, the user login time to verify the user's ID into the session, after the common class (this class is the inherited action class, and then other to use the rights
limit class to inherit the common class), use _ The Initialize () method (inheriting this class first initializes the method, which can be used to determine the user's rights). After the
, read the node used, and according to the user's ID read out the user belongs to the group (role), and then the user group to remove the Permissions table node, and finally use In_array () to determine whether the user has this node (column) If there is a display (read out of the node), no unset () method
to delete. This is achieved, the more simple way is to use the official class library to solve!
Add a few important steps below:
Build the table: in the org/util/rbac.class.php in thinkphp, there is the code for the database table (at the beginning of the file). There are four tables (node table), user-owned Group table (role), permission table (acces), User Role Table (role_user)). Create four tables but the ' user table ' is built on its own (a total of five tables), and the data is added at the end. The
may be said to be empty, the best is to go to the website to watch the video after watching this, or the relevant instructions to understand. It's not very clear, but I hope I can guide you in a direction. Also in order to help more beginners and encourage themselves to learn more to help more people, I also opened the Baidu Space (address: Hi.baidu.com/flyxiangshang). Also hope that we can support more. Many things are not you do not do, the most important thing is how long you can persist. Go up!
 

http://www.bkjia.com/PHPjc/844127.html www.bkjia.com true http://www.bkjia.com/PHPjc/844127.html techarticle thinkphp Authorization Authentication auth examples, Thinkphpauth this article in the form of instance code in depth analysis of thinkphp authorization Authentication Auth implementation principles and methods, the following steps: MySQL database ...

  • Related Article

    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.