ThinkPHP許可權認證Auth執行個體詳解,thinkphpauth
本文以執行個體代碼的形式深入剖析了ThinkPHP許可權認證Auth的實現原理與方法,具體步驟如下:
mysql資料庫部分sql代碼:
-- ------------------------------ Table structure for think_auth_group-- ----------------------------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 AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='使用者組表';-- ------------------------------ Records of think_auth_group-- ----------------------------INSERT INTO `think_auth_group` VALUES ('1', '管理組', '1', '1,2');-- ------------------------------ Table structure for think_auth_group_access-- ----------------------------DROP TABLE IF EXISTS `think_auth_group_access`;CREATE TABLE `think_auth_group_access` ( `uid` mediumint(8) unsigned NOT NULL COMMENT '使用者id', `group_id` mediumint(8) unsigned NOT NULL COMMENT '使用者組id', UNIQUE KEY `uid_group_id` (`uid`,`group_id`), KEY `uid` (`uid`), KEY `group_id` (`group_id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='使用者組明細表';-- ------------------------------ Records of think_auth_group_access-- ----------------------------INSERT INTO `think_auth_group_access` VALUES ('1', '1');INSERT INTO `think_auth_group_access` VALUES ('1', '2');-- ------------------------------ Table structure for think_auth_rule-- ----------------------------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 '' COMMENT '規則唯一標識', `title` char(20) NOT NULL DEFAULT '' COMMENT '規則中文名稱', `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '狀態:為1正常,為0禁用', `type` char(80) NOT NULL, `condition` char(100) NOT NULL DEFAULT '' COMMENT '規則運算式,為空白表示存在就驗證,不為空白表示按照條件驗證', PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`)) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='規則表';-- ------------------------------ Records of think_auth_rule-- ----------------------------INSERT INTO `think_auth_rule` VALUES ('1', 'Home/index', '列表', '1', 'Home', '');INSERT INTO `think_auth_rule` VALUES ('2', 'Home/add', '添加', '1', 'Home', '');INSERT INTO `think_auth_rule` VALUES ('3', 'Home/edit', '編輯', '1', 'Home', '');INSERT INTO `think_auth_rule` VALUES ('4', 'Home/delete', '刪除', '1', 'Home', '');DROP TABLE IF EXISTS `think_user`;CREATE TABLE `think_user` ( `id` int(11) NOT NULL, `username` varchar(30) DEFAULT NULL, `password` varchar(32) DEFAULT NULL, `age` tinyint(2) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of think_user-- ----------------------------INSERT INTO `think_user` VALUES ('1', 'admin', '21232f297a57a5a743894a0e4a801fc3', '25');
設定檔Application\Common\Conf\config.php部分:
<?phpreturn array( //'配置項'=>'配置值' 'DB_DSN' => '', // 資料庫連接DSN 用於PDO方式 'DB_TYPE' => 'mysql', // 資料庫類型 'DB_HOST' => 'localhost', // 伺服器位址 'DB_NAME' => 'thinkphp', // 資料庫名 'DB_USER' => 'root', // 使用者名稱 'DB_PWD' => 'root', // 密碼 'DB_PORT' => 3306, // 連接埠 'DB_PREFIX' => 'think_', // 資料庫表首碼 'AUTH_CONFIG' => array( 'AUTH_ON' => true, //認證開關 'AUTH_TYPE' => 1, // 認證方式,1為時時認證;2為登入認證。 'AUTH_GROUP' => 'think_auth_group', //使用者組資料表名 'AUTH_GROUP_ACCESS' => 'think_auth_group_access', //使用者組明細表 'AUTH_RULE' => 'think_auth_rule', //許可權規則表 'AUTH_USER' => 'think_user'//使用者資訊表 ));
項目Home控制器部分Application\Home\Controller\IndexController.class.php代碼:
<?phpnamespace Home\Controller;use Think\Controller;class IndexController extends Controller { public function index() { $Auth = new \Think\Auth(); //需要驗證的規則列表,支援逗號分隔的許可權規則或索引數組 $name = MODULE_NAME . '/' . ACTION_NAME; //目前使用者id $uid = '1'; //分類 $type = MODULE_NAME; //執行check的模式 $mode = 'url'; //'or' 表示滿足任一條規則即通過驗證; //'and'則表示需滿足所有規則才能通過驗證 $relation = 'and'; if ($Auth->check($name, $uid, $type, $mode, $relation)) { die('認證:成功'); } else { die('認證:失敗'); } }}
以上這些代碼就是最基本的驗證程式碼範例。
下面是源碼閱讀:
1、許可權檢驗類初始化配置資訊:
$Auth = new \Think\Auth();
建立一個對象時程式會合并配置資訊
程式會合并Application\Common\Conf\config.php中的AUTH_CONFIG數組
public function __construct() { $prefix = C('DB_PREFIX'); $this->_config['AUTH_GROUP'] = $prefix . $this->_config['AUTH_GROUP']; $this->_config['AUTH_RULE'] = $prefix . $this->_config['AUTH_RULE']; $this->_config['AUTH_USER'] = $prefix . $this->_config['AUTH_USER']; $this->_config['AUTH_GROUP_ACCESS'] = $prefix . $this->_config['AUTH_GROUP_ACCESS']; if (C('AUTH_CONFIG')) { //可設定配置項 AUTH_CONFIG, 此配置項為數組。 $this->_config = array_merge($this->_config, C('AUTH_CONFIG')); } }
2、檢查許可權:
check($name, $uid, $type = 1, $mode = 'url', $relation = 'or')
大體分析一下這個方法
首先判斷是否關閉許可權校正 如果配置資訊AUTH_ON=>false 則不會進行許可權驗證 否則繼續驗證許可權
if (!$this->_config['AUTH_ON']) { return true;}
擷取許可權列表之後會詳細介紹:
$authList = $this->getAuthList($uid, $type);
此次需要驗證的規則列錶轉換成數組:
if (is_string($name)) { $name = strtolower($name); if (strpos($name, ',') !== false) { $name = explode(',', $name); } else { $name = array($name); }}
所以$name參數是不區分大小寫,最終都會轉換成小寫
開啟url模式時全部轉換為小寫:
if ($mode == 'url') { $REQUEST = unserialize(strtolower(serialize($_REQUEST)));}
許可權校正核心程式碼片段之一,即迴圈所有該使用者權限 判斷 當前需要驗證的許可權 是否 在使用者授權列表中:
foreach ($authList as $auth) { $query = preg_replace('/^.+\?/U', '', $auth);//擷取url參數 if ($mode == 'url' && $query != $auth) { parse_str($query, $param); //擷取數組形式url參數 $intersect = array_intersect_assoc($REQUEST, $param); $auth = preg_replace('/\?.*$/U', '', $auth);//擷取訪問的url檔案 if (in_array($auth, $name) && $intersect == $param) { //如果節點相符且url參數滿足 $list[] = $auth; } } else if (in_array($auth, $name)) { $list[] = $auth; }}
in_array($auth, $name) 如果 許可權列表中 其中一條許可權 等於 當前需要校正的許可權 則加入到$list中
註:
$list = array(); //儲存驗證通過的規則名if ($relation == 'or' and !empty($list)) { return true;}$diff = array_diff($name, $list);if ($relation == 'and' and empty($diff)) { return true;}$relation == 'or' and !empty($list); //當or時 只要有一條是通過的 則 許可權為真$relation == 'and' and empty($diff); //當and時 $name與$list完全相等時 許可權為真
3、擷取許可權列表:
$authList = $this->getAuthList($uid, $type); //擷取使用者需要驗證的所有有效規則列表
這個主要流程:
擷取使用者組
$groups = $this->getGroups($uid);//SELECT `rules` FROM think_auth_group_access a INNER JOIN think_auth_group g on a.group_id=g.id WHERE ( a.uid='1' and g.status='1' )
簡化操作就是:
SELECT `rules` FROM think_auth_group WHERE STATUS = '1' AND id='1'//按正常流程 去think_auth_group_access表中內聯有點多餘....!
取得使用者組rules規則欄位 這個欄位中儲存的是think_auth_rule規則表的id用,分割
$ids就是$groups變數最終轉換成的 id數組:
$map = array( 'id' => array('in', $ids), 'type' => $type, 'status' => 1,);
取得think_auth_rule表中的規則資訊,之後迴圈:
foreach ($rules as $rule) { if (!empty($rule['condition'])) { //根據condition進行驗證 $user = $this->getUserInfo($uid); //擷取使用者資訊,一維數組 $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']); //dump($command);//debug @(eval('$condition=(' . $command . ');')); if ($condition) { $authList[] = strtolower($rule['name']); } } else { //只要存在就記錄 $authList[] = strtolower($rule['name']); } }if (!empty($rule['condition'])) { //根據condition進行驗證
這裡就可以明白getUserInfo 會去擷取設定檔AUTH_USER對應表名 去尋找使用者資訊
重點是:
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);@(eval('$condition=(' . $command . ');'));
'/\{(\w*?)\}/ 可以看成要匹配的文字為 {字串} 那麼 {字串} 會替換成$user['字串']
$command =$user['字串']
如果
$rule['condition'] = '{age}';$command =$user['age']$rule['condition'] = '{age} > 5';$command =$user['age'] > 10@(eval('$condition=(' . $command . ');'));
即:
$condition=($user['age'] > 10);
這時再看下面代碼 如果為真則加為授權列表
if ($condition) { $authList[] = strtolower($rule['name']);}
Thinkphp怎控制登陸之後人員許可權
那就註冊的時候有一個選擇管理員,普通管理員的欄位。然後登陸的時候看看是不是超級管理員
ThinkPHP:根據不同許可權顯示不同內容,該怎實現?
你說的這個問題就是thinkphp中的Rbac使用者權限問題,需要在資料庫中建立多張表來實現(這是最重要的一步)。先來說一下總的思路:
首先、使用者登陸時候驗證使用者存在之後把使用者的id存入session之中,之後在common類(這個類是繼承的action類,之後其他要用到權
限的類來繼承common類)中,使用_initialize()方法(繼承這個類的首先都要初始化這個方法,通過這個方法,可以達到使用者權限的判斷)。
之後、讀取所用的節點,並且根據使用者的id讀取出使用者所屬組(role),之後再根據使用者組取出許可權表中的節點,最後用in_array()來判斷使用者是否有這個節點(欄目)如果有則顯示(讀取出來的節點),沒有則unset()方法
刪除。這樣實現了,比較簡單的方法是使用官方的類庫解決!
下面再補充幾個重要的步驟:
建表:到thinkphp中的ORG/Util/RBAC.class.php中之后里面有建資料庫表的代碼(檔案開頭部分就有)。有四個表(節點表(node),使用者所屬組表(role),許可權表(acces),使用者角色表(role_user))。建立四張表但是‘使用者表’要自己建(總共有五張表),最後添加資料就是了。
可能說的很空洞,最好的還是去官網看點視頻之後在看這個,或者相關的說明就懂了。說的不是很清楚,但是希望能給你指導一個方向吧。也為了能幫到更多初學者和鼓勵自己學習更多來協助到更多的人,我也開通了百度空間(地址:hi.baidu.com/flyxiangshang)。也希望大家能多多支援。很多事情不是你做不做,最重要的是你能堅持多久。向上吧!
http://www.bkjia.com/PHPjc/844127.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/844127.htmlTechArticleThinkPHP許可權認證Auth執行個體詳解,thinkphpauth 本文以執行個體代碼的形式深入剖析了ThinkPHP許可權認證Auth的實現原理與方法,具體步驟如下: mysql資料庫...