如何使用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 分享