Home > PHP Framework > ThinkPHP > How to use ThinkPHP6 to implement user role permission management

How to use ThinkPHP6 to implement user role permission management

WBOY
Release: 2023-06-20 22:06:27
Original
1568 people have browsed it

With the continuous development of business, many small and medium-sized companies have their own user maintenance systems, and user rights management is an important part of it. In order to protect sensitive information in the system and ensure the normal operation of the business, we need to use a role permission management mechanism to ensure that users in different roles can only access designated resources and data.

This article will take the ThinkPHP6 framework as an example to introduce how to use the permission control middleware and extension packages it provides to implement user role permission management.

  1. Create role table and permission table

First we need to define two database tables, one is the role table, used to store system role information; the other is the permission table , used to store system permission information.

CREATE TABLE role (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
name varchar( 20) NOT NULL COMMENT 'Role name',
description varchar(50) NOT NULL COMMENT 'Role description',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='role table';

CREATE TABLE permission (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key ',
name varchar(20) NOT NULL COMMENT 'Permission name',
description varchar(50) NOT NULL COMMENT 'Permission description',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Permission table';

We can use the database migration tool provided by ThinkPHP to create the table: php think migrate :run.

  1. Create roles and permissions models

Next, we need to create roles and permissions models. Create the Role.php and Permission.php files in the app/model directory. The code is as follows:

namespace appmodel;

use thinkModel;

class Role extends Model
{

protected $table = 'role';
Copy after login

}

namespace appmodel;

use thinkModel;

class Permission extends Model
{

protected $table = 'permission';
Copy after login

}

  1. Create role and permission association table

Since a user may have multiple roles, a role may also Corresponds to multiple permissions, so we need to create an association table of roles and permissions. Create a role_permission table in the database.

CREATE TABLE role_permission (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
role_id int( 11) NOT NULL COMMENT 'Role ID',
permission_id int(11) NOT NULL COMMENT 'Permission ID',
PRIMARY KEY (id),
KEY role_id (role_id),
KEY permission_id (permission_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT ='Role-permission association table';

Define the many-to-many relationship between roles and permissions in the model:

namespace appmodel;

use thinkModel;

class Role extends Model
{

protected $table = 'role';

public function permissions()
{
    return $this->belongsToMany(
        Permission::class,
        'role_permission',
        'role_id',
        'permission_id'
    );
}
Copy after login

}

namespace appmodel;

use thinkModel;

class Permission extends Model
{

protected $table = 'permission';

public function roles()
{
    return $this->belongsToMany(
        Role::class,
        'role_permission',
        'permission_id',
        'role_id'
    );
}
Copy after login

}

  1. Define middleware

In ThinkPHP6, the middleware is A powerful tool for processing requests, we can implement permission control through middleware. Create a CheckAuth middleware to determine whether the user has permission to perform the current operation. Create the CheckAuth.php file in the appmiddleware directory with the following code:

namespace appmiddleware;

use think acadeDb;
use think acadeSession;
use think acadeConfig;

class CheckAuth
{

public function handle($request, Closure $next)
{
    if (Session::has('user')) {
        $roles = Db::table('user')
            ->alias('u')
            ->leftJoin('role_user ru', 'u.id = ru.user_id')
            ->leftJoin('role r', 'ru.role_id = r.id')
            ->where('u.id', '=', Session::get('user')->id)
            ->field('r.id')
            ->select();
        $permissions = Config::get('permissions');
        foreach ($roles as $role) {
            $rolePermissions = Db::table('role_permission')
                ->where('role_id', '=', $role->id)
                ->field('permission_id')
                ->select();
            foreach ($rolePermissions as $rolePermission) {
                if (in_array($rolePermission->permission_id, $permissions)) {
                    return $next($request);
                }
            }
        }
    }
    abort(403, '没有权限');
}
Copy after login

}

This middleware will first query all roles owned by the current user. When traversing the roles, query each If the permissions owned by a role match the current request, execution will be allowed to continue, otherwise a 403 error will be returned.

  1. Create permission configuration file

In order to facilitate the management of system permissions, we can use the Config function provided by ThinkPHP to write all permissions into the configuration file. Create a permissions.php file in the config directory. The code is as follows:

return [

1 => 'user.create',
2 => 'user.read',
3 => 'user.update',
4 => 'user.delete',
Copy after login

];

We can pass key/value To record all the permissions of the system, the key is an integer and the value is a string, indicating the name of the permission.

  1. Applying middleware

Finally, we need to actually apply the above middleware. Open the middleware.php file in the config directory and add the CheckAuth middleware.

return [

// ...
'check_auth' => appmiddlewareCheckAuth::class,
Copy after login

];

The application order of middleware is executed from front to back according to the key name of the array. We can Adjust the execution order of middleware through array subscripts.

On the controller or method that requires permission control, you can use the middleware method to bind the CheckAuth middleware.

namespace appcontroller;

use think acadeView;

class UserController
{

public function create()
{
    $this->middleware('check_auth');
    // ...
}
Copy after login

}

So far, we have completed all the steps to implement user role permission management using ThinkPHP6. You can expand and improve the above sample code according to actual business needs.

The above is the detailed content of How to use ThinkPHP6 to implement user role permission management. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template