在開發基于 thinkphp6 的項目時,權限管理是一個關鍵的功能模塊。最初,我嘗試通過手動編寫代碼來處理用戶權限,但這不僅耗時,而且容易出錯。幸運的是,我找到了 itkee/think-auth 這個強大的權限管理庫,通過 composer 輕松解決了我的問題。
安裝與配置
使用 Composer 安裝 itkee/think-auth 非常簡單,只需運行以下命令:
composer require itkee/think-auth
安裝完成后,需要在項目配置文件中進行一些設置。以下是一個基本的配置示例:
'auth' => [ 'auth_on' => 1, // 權限開關 'auth_type' => 1, // 認證方式,1為實時認證;2為登錄認證。 'auth_group' => 'auth_group', // 用戶組數據不帶前綴表名 'auth_group_Access' => 'auth_group_access', // 用戶-用戶組關系不帶前綴表名 'auth_rule' => 'auth_rule', // 權限規則不帶前綴表名 'auth_user' => 'member', // 用戶信息不帶前綴表名 ],
此外,還需要導入必要的數據表。這些表包括規則表(think_auth_rule)、用戶組表(think_auth_group)和用戶組明細表(think_auth_group_access)。以下是創建這些表的 sql 語句:
立即學習“PHP免費學習筆記(深入)”;
DROP TABLE IF EXISTS `think_auth_rule`; CREATE TABLE `think_auth_rule` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `name` char(80) NOT NULL DEFAULT '', `title` char(20) NOT NULL DEFAULT '', `status` tinyint(1) NOT NULL DEFAULT '1', `condition` char(100) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `think_auth_group`; CREATE TABLE `think_auth_group` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `title` char(100) NOT NULL DEFAULT '', `status` tinyint(1) NOT NULL DEFAULT '1', `rules` char(80) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `think_auth_group_access`; CREATE TABLE `think_auth_group_access` ( `uid` mediumint(8) unsigned NOT NULL, `group_id` mediumint(8) unsigned NOT NULL, UNIQUE KEY `uid_group_id` (`uid`,`group_id`), KEY `uid` (`uid`), KEY `group_id` (`group_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
使用方法
itkee/think-auth 庫的使用非常靈活。以下是幾個常見的使用場景:
-
檢測用戶權限:
// 檢測權限 if($auth->check('show_button',1)){ // 第一個參數是規則名稱,第二個參數是用戶UID //有顯示操作按鈕的權限 }else{ //沒有顯示操作按鈕的權限 }
-
節點認證:
可以通過在公共控制器中定義 _initialize 方法來實現:
<?php use thinkController; use thinkauthAuth; class Base extends Controller { public function _initialize() { $controller = request()->controller(); $action = request()->action(); $auth = new Auth(); if(!$auth->check($controller . '-' . $action, session('uid'))){ $this->error('你沒有權限訪問'); } } }
-
多規則認證:
可以同時對多個規則進行認證,支持 or 和 and 關系:
$auth->check('rule1,rule2', uid); // or 關系 $auth->check('rule1,rule2', uid, 'and'); // and 關系
-
獲取用戶組:
$auth->getGroups(uid);
-
按用戶屬性判斷權限:
可以根據用戶屬性(如積分)進行權限判斷:
// 規則表中的 condition 字段 // name: grade1, condition: {score}<100 // name: grade2, condition: {score}>100 and {score}<200 // name: grade3, condition: {score}>200 and {score}<300 $auth->check('grade1', uid); // 判斷用戶積分是不是0-100 $auth->check('grade2', uid); // 判斷用戶積分是不是在100-200 $auth->check('grade3', uid); // 判斷用戶積分是不是在200-300
總結
使用 itkee/think-auth 庫通過 Composer 進行權限管理,不僅簡化了開發流程,還大大提高了代碼的可維護性和擴展性。通過這個庫,我能夠快速實現復雜的權限控制邏輯,極大地提升了項目的效率和安全性。如果你也在 ThinkPHP6 項目中遇到權限管理問題,不妨試試這個庫,相信會給你帶來意想不到的效果。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END