如何使用Hyperf框架进行权限控制

如何使用Hyperf框架进行权限控制

如何使用Hyperf框架进行权限控制

引言:
在开发一个应用程序时,往往需要实现权限控制功能,以不同的角色给予用户不同的权限。Hyperf框架是一个高性能的php微服务框架,提供了许多强大的功能和扩展,其中包括灵活的权限控制。在本文中,我们将探讨如何使用Hyperf框架实现权限控制,并提供具体的代码示例。

一、创建权限表
首先,我们需要创建一个权限表,用于存储各种权限信息。可以通过Hyperf的数据迁移功能来创建数据库表。在终端中执行以下命令来生成迁移文件:

php bin/hyperf.php gen:migration create_permissions_table

然后在生成的迁移文件中添加以下内容:

<?php use HyperfDatabaseSchemaSchema; use HyperfDatabaseSchemaBlueprint; use HyperfDatabaseMigrationsMigration; use HyperfDbConnectionDb;  class CreatetPermissionsTable extends Migration {     /**      * Run the migrations.      */     public function up(): void     {         $tableName = 'permissions';         $exists = Db::table('information_schema.TABLES')             ->where('TABLE_SCHEMA', config('databases.default.dbname'))             -&gt;where('TABLE_NAME', $tableName)             -&gt;first();          if (!$exists) {             Schema::create($tableName, function (Blueprint $table) {                 $table-&gt;bigIncrements('id');                 $table-&gt;string('name')-&gt;unique()-&gt;comment('权限名称');                 $table-&gt;string('guard_name')-&gt;default('web')-&gt;comment('守卫名称');                 $table-&gt;timestamps();             });         }     }      /**      * Reverse the migrations.      */     public function down(): void     {         Schema::dropIfExists('permissions');     } }

接下来,我们需要在项目的主配置文件config/autoload/permissions.php中添加以下内容:

<?php return [     'default' => [         'guard_name' =&gt; 'web',         'permissions' =&gt; [             // 在这里添加你的权限             'create_post',             'edit_post',             'delete_post',             // ...         ],     ], ];

然后在命令行中运行以下命令执行数据库迁移:

php bin/hyperf.php migrate

二、定义用户角色模型
在Hyperf框架中,我们需要定义一个用户模型,该模型用于管理用户的角色和权限。我们可以通过继承HyperfDatabaseModelModel类来创建一个用户模型。在终端中执行以下命令来生成用户模型:

php bin/hyperf.php gen:model User

然后在生成的用户模型文件中添加以下代码:

namespace AppModel;  use HyperfDbConnectionModelModel; use HyperfUtilsApplicationContext;  class User extends Model {     protected $guarded = [];      public function roles()     {         return $this-&gt;belongsToMany(Role::class);     }      public function hasPermission($permission)     {         foreach ($this-&gt;roles as $role) {             if ($role-&gt;hasPermission($permission)) {                 return true;             }         }         return false;     }      public function givePermission($permission)     {         $permissionModel = Permission::where('name', $permission)-&gt;first();         if (!$permissionModel) {             throw new Exception("Permission {$permission} does not exist.");         }         $this-&gt;permissions()-&gt;sync($permissionModel, false);     }      public function revokePermission($permission)     {         $permissionModel = Permission::where('name', $permission)-&gt;first();         if (!$permissionModel) {             throw new Exception("Permission {$permission} does not exist.");         }         $this-&gt;permissions()-&gt;detach($permissionModel);     }      public function permissions()     {         return $this-&gt;belongsToMany(Permission::class, 'user_permissions');     } }

三、定义角色模型
在Hyperf框架中,我们也需要定义一个角色模型,该模型用于管理角色和权限。同样,我们可以通过继承HyperfDatabaseModelModel类来创建一个角色模型。在终端中执行以下命令来生成角色模型:

php bin/hyperf.php gen:model Role

然后在生成的角色模型文件中添加以下代码:

namespace AppModel;  use HyperfDbConnectionModelModel;  class Role extends Model {     protected $guarded = [];      public function users()     {         return $this-&gt;belongsToMany(User::class);     }      public function permissions()     {         return $this-&gt;belongsToMany(Permission::class);     }      public function hasPermission($permission)     {         return $this-&gt;permissions-&gt;contains('name', $permission);     }      public function givePermission($permission)     {         $permissionModel = Permission::where('name', $permission)-&gt;first();         if (!$permissionModel) {             throw new Exception("Permission {$permission} does not exist.");         }         $this-&gt;permissions()-&gt;sync($permissionModel, false);     }      public function revokePermission($permission)     {         $permissionModel = Permission::where('name', $permission)-&gt;first();         if (!$permissionModel) {             throw new Exception("Permission {$permission} does not exist.");         }         $this-&gt;permissions()-&gt;detach($permissionModel);     } }

四、定义权限模型
在Hyperf框架中,我们还需要定义一个权限模型,该模型用于管理权限信息。同样地,我们可以通过继承HyperfDatabaseModelModel类来创建一个权限模型。在终端中执行以下命令来生成权限模型:

php bin/hyperf.php gen:model Permission

然后在生成的权限模型文件中添加以下代码:

namespace AppModel;  use HyperfDbConnectionModelModel;  class Permission extends Model {     protected $guarded = [];      public function roles()     {         return $this-&gt;belongsToMany(Role::class);     } }

五、定义权限中间件
接下来,我们需要创建一个权限中间件,用于检查用户是否有足够的权限访问某个路由。在终端中执行以下命令来生成中间件:

php bin/hyperf.php gen:middleware PermissionMiddleware

然后在生成的中间件文件中添加以下代码:

namespace AppMiddleware;  use HyperfHttpMessageStreamSwooleStream; use HyperfHttpServerContractRequestInterface; use HyperfUtilsContext; use PsrContainerContainerInterface; use PsrHttpMessageResponseInterface; use PsrHttpServerMiddlewareInterface; use PsrHttpServerRequestHandlerInterface;  class PermissionMiddleware implements MiddlewareInterface {     protected $container;      protected $request;      public function __construct(ContainerInterface $container, RequestInterface $request)     {         $this-&gt;container = $container;         $this-&gt;request = $request;     }      public function process($request, RequestHandlerInterface $handler): ResponseInterface     {         $user = $this-&gt;request-&gt;getAttribute('user');         $permissions = $this-&gt;request-&gt;route-&gt;permission;          if ($user &amp;&amp; $user-&gt;hasPermission($permissions)) {             return $handler-&gt;handle($request);         }          return $this-&gt;response(403, 'Forbidden');     }      protected function response($code, $message)     {         $data = [             'code' =&gt; $code,             'message' =&gt; $message,         ];          return Context::get(ResponseInterface::class)-&gt;withBody(new SwooleStream(json_encode($data)));     } }

六、使用权限中间件
在路由定义中,我们可以通过使用->middleware(‘permission:xxx’)来给路由设置对应的权限中间件。在终端中执行以下命令来生成路由文件:

php bin/hyperf.php gen:controller PermissionController

然后在生成的路由文件中添加以下代码:

namespace AppController;  use AppMiddlewarePermissionMiddleware; use HyperfHttpServerAnnotationController; use HyperfHttpServerAnnotationMiddleware; use HyperfHttpServerAnnotationRequestMapping;  /**  * @Controller  * @Middleware(PermissionMiddleware::class)  */ class PermissionController {     /**      * @RequestMapping(path="/permission", methods="get")      * @Middleware("permission:create_post")      */     public function createPost()     {         // 处理创建文章的逻辑     }      /**      * @RequestMapping(path="/permission", methods="get")      * @Middleware("permission:edit_post")      */     public function editPost()     {         // 处理编辑文章的逻辑     }      /**      * @RequestMapping(path="/permission", methods="get")      * @Middleware("permission:delete_post")      */     public function deletePost()     {         // 处理删除文章的逻辑     } }

七、使用示例
在需要进行权限控制的地方,我们可以通过以下方式来检查用户是否拥有足够的权限:

$user = User::find(1);  if ($user-&gt;hasPermission('edit_post')) {     // 给用户权限来编辑文章 } else {     // 权限不足 }

八、总结
本文介绍了如何使用Hyperf框架进行权限控制的详细步骤,并提供了具体的代码示例。通过使用Hyperf框架提供的权限管理功能,我们可以轻松地为我们的应用程序实现灵活的权限控制功能。希望本文对您有所帮助,谢谢阅读!

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享