Home  >  Article  >  PHP Framework  >  ThinkPHP6 Permission Management Guide: Implementing User Permission Control

ThinkPHP6 Permission Management Guide: Implementing User Permission Control

王林
王林Original
2023-08-13 18:09:072014browse

ThinkPHP6 Permission Management Guide: Implementing User Permission Control

ThinkPHP6 Permission Management Guide: Implementing User Permission Control

Introduction:
In web applications, permission management is a very important part, it can help We control users' access and operation rights to system resources and protect the security of the system. In the ThinkPHP6 framework, we can use its powerful permission management functions to implement user permission control.

1. Create a database table
Before we start to implement user permission control, we first need to create the corresponding database table to store user, role and permission information. The following is the SQL statement to create the table:

  1. User table (user):
    CREATE TABLE user (
    id int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
    username varchar(50) NOT NULL COMMENT 'Username',
    password char(32) NOT NULL COMMENT ' Password',
    PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User table';
  2. Role table (role):
    CREATE TABLE role (
    id int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'role ID',
    name varchar(50) NOT NULL COMMENT 'role name',
    PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='role table';
  3. Permission table (permission):
    CREATE TABLE permission (
    id int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Permission ID',
    name varchar(50 ) NOT NULL COMMENT 'Permission name',
    PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Permission table';
  4. User-role Association table (user_role):
    CREATE TABLE user_role (
    user_id int(11) unsigned NOT NULL COMMENT 'User ID',
    role_id int(11) unsigned NOT NULL COMMENT 'role ID',
    PRIMARY KEY (user_id,role_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT= 'User-role association table';
  5. Role-permission association table (role_permission):
    CREATE TABLE role_permission (
    role_id int(11) unsigned NOT NULL COMMENT 'Role ID',
    permission_id int(11) unsigned NOT NULL COMMENT 'Permission ID',
    PRIMARY KEY (role_id,permission_id )
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Role-Permission Association Table';

2. Define model association
In ThinkPHP6, we can use models Associations to establish relationships between users, roles, and permissions. The following is the corresponding model definition:

  1. User model (User.php):
    namespace appmodel;

use thinkModel;

class User extends Model
{

// 用户-角色关联
public function roles()
{
    return $this->belongsToMany(Role::class, 'user_role');
}

}

  1. Role Model (Role.php):
    namespace appmodel;

use thinkModel;

class Role extends Model
{

// 角色-权限关联
public function permissions()
{
    return $this->belongsToMany(Permission::class, 'role_permission');
}

}

  1. Permission model (Permission.php):
    namespace appmodel;

use thinkModel;

class Permission extends Model
{

// 权限-角色关联
public function roles()
{
    return $this->belongsToMany(Role::class, 'role_permission');
}

}

3. Define permission middleware
In ThinkPHP6, we can use Middleware to uniformly handle the verification of user permissions. The following is a simple permission middleware definition example:

  1. Create a middleware class:
    namespace appmiddleware;

use appmodelPermission;
use think acadeRequest;
use think acadeSession;
use thinkResponse;

class AuthMiddleware
{

public function handle(Request $request, Closure $next)
{
    // 获取当前请求的URL
    $url = $request->baseUrl();

    // 获取当前用户的角色信息
    $roles = Session::get('user.roles');

    // 获取当前角色拥有的权限
    $permissions = [];
    foreach ($roles as $role) {
        $rolePermissions = Permission::whereHas('roles', function ($query) use ($role) {
            $query->where('role_id', $role['id']);
        })->select();
        $permissions = array_merge($permissions, $rolePermissions->toArray());
    }

    // 验证权限
    foreach ($permissions as $permission) {
        if ($permission['name'] == $url) {
            return $next($request);
        }
    }

    // 没有权限,跳转到无权限页面
    return Response::create('您没有权限访问该页面!', 'html', 403);
}

}

  1. Registration middleware:
    us The permission middleware can be registered in the application's middleware configuration file (middleware.php) as follows:
    return [
    // ...
    ppmiddlewareAuthMiddleware::class,
    / / ...
    ];

4. Apply permission middleware
We can apply permission verification by using middleware in the routing definition. The following is an example route definition:

use think acadeRoute;

Route::group('admin', function () {

// 需要验证权限的页面
Route::rule('user/index', 'admin/user/index')
    ->middleware('AuthMiddleware');
// ...
// 其他路由定义
// ...

})->middleware( 'AuthMiddleware');

In the above example, we apply permission middleware by using the middleware('AuthMiddleware') method to achieve verification and control of user permissions.

Conclusion:
Through the above steps, we can realize the management and control of user permissions in the ThinkPHP6 framework. Using model association and middleware, we can easily realize the relationship between users, roles and permissions, and use middleware to perform permission verification and intercept and process when users access restricted pages. This can effectively protect the security of system resources and provide the system with better user permission control functions.

The above is the detailed content of ThinkPHP6 Permission Management Guide: Implementing User Permission Control. 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