search
HomeBackend DevelopmentPHP TutorialA brief discussion on the seventh bullet of PHP - role-based access control RBAC_PHP tutorial

The above http://www.BkJia.com/kf/201205/129972.html explains to you how to use a loop to output the multiplication table. The logic is relatively simple, but the important thing is to provide you with a program to read it. , methods and ideas for parsing the code, if you have any comments or suggestions, you can comment and criticize....

Okay, no more talk, this article will introduce to you "role-based access control",

When it comes to permissions, everyone has a headache. How can we flexibly control a user’s permissions?

Some students will add fields to the user table or corresponding permission fields to the role table,

There will be a problem with this. It feels very lame and inflexible to implement permissions. Every time a permission is added, a field will be added to the database, which is not conducive to the iterative development of the project

Then we need a very flexible design pattern RBAC, that is, role-based access control;

Let me tell you about this design idea:

First of all, our requirement is to determine whether a user has permission to access the currently operated controller or controller method,

If multiple users have the same permissions at the same time, then we need to assign the same user role to these users, and then only need to control access to operations through the role,

Then our table structure needs to be designed like this. This is very important, as follows:

First data table (user table):

字段名称 字段说明
id 用户ID(主键自增)
username 用户名
password 用户密码

Second data sheet (character sheet):

字段名称 字段说明
id 用户角色ID(主键自增)
name 用户角色名称
   

The third data table (node ​​table):

字段名称 字段说明
id 操作节点ID(主键自增)
name 操作节点的名称
zh_name 节点的中文说明

We use the third normal form to design the association table. The advantage of this is to avoid data redundancy, and one-to-many and many-to-one relationships can be clearly recorded and organized

The fourth data table (node ​​corresponding role table):

字段名称 字段说明
role_id 用户角色ID(外键,关联角色表中的主键ID)
note_id 操作节点ID(外键,关联节点表中的主键ID)
   

The fifth data table (user corresponding role table):

字段名称 字段说明
role_id 用户角色ID(外键,关联角色表中的主键ID)
user_id 用户ID(外键,关联用户表中的主键ID)
   

Access control can be carried out through these five tables. The specific operation steps are as follows:

User enters username and password to log in,
Judging from the user table, if the entered user name and password are illegal, jump back and log in again
If legal, return the user's ID number in the user table,
Through this user ID number, query the user's role ID number in the association table between the user and the role,
Get the role ID number, and use this ID number to query the association table between roles and nodes to find out the node access rights owned by this role,
Store all the permission nodes in SESSION. When the user accesses a certain module,

For example: http://www.lampbroher.net/index.php/stu/index

We use the permissions in the session to compare with $_GET['m'] and $_GET['a'],

If $_GET['m'] or $_GET['a'] does not exist in SESSION, it means that the user does not have this permission, just handle it.

Reference code:

RBAC class file:
/*+-------------------------------------------------- ----------------------------------------+
| RBAC permission control class

class Rbac{
private $node_tablename; //Define private attribute node table name
private $group_auth_tablename; //Define private attribute group permission table name
private $group_tablename; //Define private attribute user group table name
private $group_user_tablename; //Define private attribute user belonging group table name
private $user_tablename; //Define private attribute user table name
/*
Construction method
@param1 string node table name
@param2 string user permission table name
@param3 string user group table name
@param4 string user belonging group table name
@param5 string user table name
*/
public function __construct($node_tablename='node',$group_auth_tablename='group_auth',$group_tablename='group',$group_user_tablename='group_member',$user_tablename='member'){
$this->node_tablename = $node_tablename; //Get the node table name
$this->group_auth_tablename = $group_auth_tablename; //Get the user permission table name
$this->group_tablename = $group_tablename; //Get the user group table name
$this->group_user_tablename = $group_user_tablename; //Get the user belonging group table name
$this->user_tablename = $user_tablename; //Get the user table name
}
/*
Set node method
@param1 string node name
@param2 string node parent ID
@param2 string node Chinese description
@return int ID after successful insertion of node record
*/
public function set_node($name,$pid,$zh_name=''){
if(!empty($name) && !empty($pid)){
$node = D($this->node_tablename)->insert(array("name"=>$name,"pid"=>$pid,"zh_name"=>$zh_name));
}
return $node;
}
/*
How to set permissions
@param1 int group ID
@param2 int node ID
@return int ID after inserting permission record successfully
*/
public function set_auth($gid,$nid){
if(!empty($gid) && !empty($nid)){
$auth = D($this->group_auth_tablename)->insert(array("gid"=>$gid,"nid"=>$nid));
}
return $auth;
}
/*
Get node method
@param1 int node ID
@return array Get the relevant information of the node table
*/
public function get_node($id){
if(!empty($id)){
$data = D($this->node_tablename)->field("id,name,pid")->where(array('id'=>$id))->find();
return $data;
}else{
return false;
}
}
/*
How to obtain group permissions
@param1 int user group ID
@return array Get relevant information about the group permission table
*/
public function get_auth($gid){
if(!empty($gid)){
$data = D($this->group_auth_tablename)->field("nid")->where(array('gid'=>$gid))->select();
return $data;
}else{
return false;
}
}
/*
Get user group method
@param1 int user ID
@return array Get the user group id corresponding to the user
*/
public function get_group($uid){
if(!empty($uid)){
$data = D($this->group_user_tablename)->field("gid")->where(array('uid'=>$uid))->select();
return $data;
}else{
return false;
}
}
/*
Get the child node method of a node
@param1 int node ID
@return array Get all the child nodes corresponding to this node
*/
public function get_cnode($nid){
if(!empty($nid)){
$cnode = D($this->node_tablename)->field("name")->where(array('pid'=>$nid))->select();
return $cnode;
}else{
return false;
}
}
/*
How to obtain permission
@param1 int user ID
@return array Get the permission list
*/
public function get_access($uid){
if(!empty($uid)){
//Call the method to get group information
$group = $this->get_group($uid);
//Traverse group information
foreach($group as $v){
//Pass the group ID into the method to obtain permissions
$auth = $this->get_auth($v['gid']); //Get the permissions of the group
}
//Traverse the permission array of the group
foreach($auth as $val){
//Pass the ID of the node into the method of obtaining node information
$node[] = $this->get_node($val['nid']); //Get node-related information
}
//Traverse the node array and assemble it
foreach($node as $nval){
if($nval['pid']==0){
$fnode[] = $nval; //Push the controller into the fnode array
//$cnode = $this->get_cnode($nval['id']);
}else{
$cnode[] = $nval; //Push the controller method into the cnode array
}
}
//Assemble the controller array and the controller array into an array
foreach($fnode as $fval){
foreach($cnode as $cval){
if($cval['pid'] == $fval['id']){
$access[$fval['name']][] = $cval['name'];
}
}
}
//Return permission list array
return $access;
}else{
return false;
}
}
/*
How to check permissions
@param1 int user ID
@return boolean Whether permission is prohibited
*/
public function check($uid){
if(!empty($uid)){
//Save permissions into $_SESSION['Access_List']
$_SESSION['Access_List'] = $this->get_access($uid);
if(!empty($_GET['m'])){
//Determine whether this controller is allowed
if(array_key_exists($_GET['m'],$_SESSION['Access_List'])){
//Determine whether the method of this controller is allowed
if(in_array($_GET['a'],$_SESSION['Access_List'][$_GET['m']])){
//Return true if allowed
return true;
}else{
// Otherwise return false
return false;
}
}else{
return false;
}
}else{
return false;
}
}else{
//$_SESSION['user_'.$uid]['Access_List'] = 0;
return false;
}
}
public function show_node(){
$path = APP_PATH.'/controls/';
$handle = opendir($path);
while(false!==($data = readdir($handle))){
if(is_file($path.$data) && $data!='common.class.php' && $data!='pub.class.php'){
$controller = str_replace(".class.php",'',$data);
$res = fopen($path.$data,'r');
$str = fread($res,filesize($path.$data));
$pattern = '/function(.*)()/iU';
preg_match_all($pattern, $str, $matches);
foreach($matches[1] as $v){
$v = trim($v);
$arr[$controller][] = $v;
}
}
}
closedir($handle);
return $arr;
}
}
Initialization class:
/*+-------------------------------------------------- ----------------------------------------+
| Initialize controller

class Common extends Action {
/*
Initialization method
*/
public function init(){
//If SESSION is empty, jump
if(empty($_SESSION['user_login'])){
$this->redirect("pub/index");
}
$a = new rbac();
if(!$a->check($_SESSION['user_info']['id'])){
echo "<script>alert('You do not have this permission!')</script>";
exit("<script>document.write('<span style='font-size:40px;font-weight:bold'>Access Forbidden');alert('You do not have this permission!');< /script>");<br /> $this->redirect("pub/index");<br /> }<br /> }<br /> }</script>

Here I wrote a simple RBAC class for everyone, just for everyone to learn and refer to this idea. If you have any questions, you can leave a reply....


Author zdrjlamp

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478251.htmlTechArticleThe above http://www.2cto.com/kf/201205/129972.html explains how to use it. Looping to output the multiplication table is relatively simple logically. The main point is to provide everyone with a way to view the program and analyze it...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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