* ## 一.先創建數據表
~~~
----------------------------------------------------------------------------
-- auth_rule,規則表,
-- id:主鍵,
-- src:規則唯一標識, title:規則中文名稱 status 狀態:為1正常,為0禁用
-- src 可以自定義名稱,也可以是模塊/控制器/方法、模塊_控制器_方法、控制器/方法、控制器_方法、控制器-方法
-- condition:規則表達式,為空表示存在就驗證,不為空表示按照條件驗證
-- condition 簡單來說,如果字段為空,則只驗證name就行;如果字段不為空,則在驗證了name的基礎上,還要驗證字段里面的條件
-- condition 條件,是user表的字段條件(準確來說,是auth_user配置的表),如 {score} > 10
----------------------------------------------------------------------------
DROP TABLE IF EXISTS `auth_rule`;
CREATE TABLE `auth_rule` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`src` varchar(80) NOT NULL DEFAULT '',
`title` varchar(20) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT 1,
`condition` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`src`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
----------------------------------------------------------------------------
-- auth_group 用戶組表,
-- id:主鍵, title:用戶組中文名稱, rules:用戶組擁有的規則id, 多個規則","隔開,status 狀態:為1正常,為0禁用
----------------------------------------------------------------------------
DROP TABLE IF EXISTS `auth_group`;
CREATE TABLE `auth_group` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT 1,
`rules` varchar(80) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
----------------------------------------------------------------------------
-- auth_group_access 用戶-用戶組關系表
-- uid:用戶id,group_id:用戶組id
----------------------------------------------------------------------------
DROP TABLE IF EXISTS `auth_group_access`;
CREATE TABLE `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=InnoDB DEFAULT CHARSET=utf8mb4;
~~~
* ## 二.在使用Auth類前需要配置config.php
~~~
// auth配置 自定義數據表位置在 ./config/auth.php里面
[
'auth_on' => 1, // 權限開關
'auth_type' => 1, // 認證方式,1為實時認證;2為登錄認證。
'auth_group' => 'auth_group', // 用戶組數據表(不帶前綴表名)
'auth_group_access' => 'auth_group_access', // 用戶-用戶組關系表(不帶前綴表名)
'auth_rule' => 'auth_rule', // 權限規則表(不帶前綴表名)
'auth_user' => 'user', // 用戶信息表(不帶前綴表名)
]
// 注意:condition里的變量是用戶表(配置auth_user的值的表,通常配置為用戶表)的字段
// (當然,不配置auth_user的值為用戶表,而是其他表,那也行的!但是,condition里的變量只能是配置的表里面的字段)
// (如配置auth_user的值為integral積分表,那么condition里的變量就只能是integral表里面的字段)
// condition里的變量用花括號括住,如:{score}
// 表的前綴在框架的數據庫配置那配置,這里的配置的表都是不帶前綴的
~~~
* ## 三.新建Auth類 ./extend/lib/Auth.php
```
<?php
namespace lib;
use think\facade\Db;
use think\facade\Config;
use think\facade\Session;
use think\facade\Request;
/**
* 權限認證類
* 功能特性:
* 1,是對規則進行認證,不是對節點進行認證。用戶可以把節點當作規則名稱實現對節點進行認證。
* $auth=new Auth(); $auth->check('規則名稱','用戶id')
* 2,可以同時對多條規則進行認證,并設置多條規則的關系(or或者and)
* $auth=new Auth(); $auth->check('規則1,規則2','用戶id','and')
* 第三個參數為and時表示,用戶需要同時具有規則1和規則2的權限。 當第三個參數為or時,表示用戶值需要具備其中一個條件即可。默認為or
* 3,一個用戶可以屬于多個用戶組(auth_group_access表 定義了用戶所屬用戶組)。我們需要設置每個用戶組擁有哪些規則(auth_group 定義了用戶組權限)
*
* 4,支持規則表達式。
* 在auth_rule 表中定義一條規則時,如果type為1, condition字段就可以定義規則表達式。 如定義{score}>5 and {score}<100 表示用戶的分數在5-100之間時這條規則才會通過。
*/
class Auth
{
/**
* var object 對象實例
*/
protected static $instance;
//默認配置
protected $config = [
'auth_on' => 1, // 權限開關
'auth_type' => 1, // 認證方式,1為實時認證;2為登錄認證。
'auth_group' => 'admin_group', // 用戶組數據表名
'auth_group_access' => 'admin_group_access', // 用戶-用戶組關系表
'auth_rule' => 'menu', // 權限規則表
'auth_user' => 'manager', // 用戶信息表
];
/**
* 類架構函數
* Auth constructor.
*/
public function __construct()
{
//可設置配置項 auth, 此配置項為數組。
if ($auth = Config::get('auth')) {
$this->config = array_merge($this->config, $auth);
}
}
/**
* 初始化
* access public
* @param array $options 參數
* return \think\Request
*/
public static function instance($options = [])
{
if (is_null(self::$instance)) {
self::$instance = new static($options);
}
return self::$instance;
}
/**
* 檢查權限
* @param $name string|array 需要驗證的規則列表,支持逗號分隔的權限規則或索引數組
* @param $uid int 認證用戶的id
* @param int $type 認證類型
* @param string $mode 執行check的模式
* @param string $relation 如果為 'or' 表示滿足任一條規則即通過驗證;如果為 'and'則表示需滿足所有規則才能通過驗證
* return bool 通過驗證返回true;失敗返回false
*/
public function check($name, $uid, $type = 1, $mode = 'url', $relation = 'or')
{
if (!$this->config['auth_on']) {
return true;
}
// 獲取用戶需要驗證的所有有效規則列表
$authList = $this->getAuthList($uid, $type);
// dump($authList);
if (is_string($name)) {
$name = strtolower($name);
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = [$name];
}
}
$list = []; //保存驗證通過的規則名
if ('url' == $mode) {
$REQUEST = unserialize(strtolower(serialize(Request::param())));
}
foreach ($authList as $auth) {
$query = preg_replace('/^.+\?/U', '', $auth);
if ('url' == $mode && $query != $auth) {
parse_str($query, $param); //解析規則中的param
$intersect = array_intersect_assoc($REQUEST, $param);
$auth = preg_replace('/\?.*$/U', '', $auth);
if (in_array($auth, $name) && $intersect == $param) {
//如果節點相符且url參數滿足
$list[] = $auth;
}
} else {
if (in_array($auth, $name)) {
$list[] = $auth;
}
}
}
// dump($list);
// dump($name);
if ('or' == $relation && !empty($list)) {
return true;
}
$diff = array_diff($name, $list);
if ('and' == $relation && empty($diff)) {
return true;
}
return false;
}
/**
* 根據用戶id獲取用戶組,返回值為數組
* @param $uid int 用戶id
* return array 用戶所屬的用戶組 array(
* array('uid'=>'用戶id','group_id'=>'用戶組id','title'=>'用戶組名稱','rules'=>'用戶組擁有的規則id,多個,號隔開'),
* ...)
*/
public function getGroups($uid)
{
static $groups = [];
if (isset($groups[$uid])) {
return $groups[$uid];
}
// 轉換表名
$auth_group_access = $this->config['auth_group_access'];
$auth_group = $this->config['auth_group'];
// 執行查詢
$user_groups = Db::view($auth_group_access, 'uid,group_id')
->view($auth_group, 'title,rules', "{$auth_group_access}.group_id={$auth_group}.id", 'LEFT')
->where("{$auth_group_access}.uid='{$uid}' and {$auth_group}.status='1'")
->select();
$groups[$uid] = $user_groups ?: [];
return $groups[$uid];
}
/**
* 獲得權限列表
* @param integer $uid 用戶id
* @param integer $type
* return array
*/
protected function getAuthList($uid, $type)
{
static $_authList = []; //保存用戶驗證通過的權限列表
$t = implode(',', (array)$type);
if (isset($_authList[$uid . $t])) {
return $_authList[$uid . $t];
}
if (2 == $this->config['auth_type'] && Session::has('_auth_list_' . $uid . $t)) {
return Session::get('_auth_list_' . $uid . $t);
}
//讀取用戶所屬用戶組
$groups = $this->getGroups($uid);
$ids = []; //保存用戶所屬用戶組設置的所有權限規則id
foreach ($groups as $g) {
$ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
}
$ids = array_unique($ids);
if (empty($ids)) {
$_authList[$uid . $t] = [];
return [];
}
$map = [
['type','=',$type],
['smid','in', $ids],
// ['status','=',0],
];
//讀取用戶組所有權限規則
$rules = Db::name($this->config['auth_rule'])->where($map)->field('condition,src')->select();
//循環規則,判斷結果。
$authList = []; //
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['src']);
}
} else {
//只要存在就記錄
$authList[] = strtolower($rule['src']);
}
}
$_authList[$uid . $t] = $authList;
if (2 == $this->config['auth_type']) {
//規則列表結果保存到session
Session::set('_auth_list_' . $uid . $t, $authList);
}
return array_unique($authList);
}
/**
* 獲得用戶資料,根據自己的情況讀取數據庫
*/
function getUserInfo($uid)
{
static $userinfo = [];
$user = Db::name($this->config['auth_user']);
// 獲取用戶表主鍵
$_pk = is_string($user->getPk()) ? $user->getPk() : 'uid';
if (!isset($userinfo[$uid])) {
$userinfo[$uid] = $user->where($_pk, $uid)->find();
}
return $userinfo[$uid];
}
//根據uid獲取角色名稱
//根據uid獲取角色名稱
function getRole($uid){
try{
$auth_group_access = Db::name($this->config['auth_group_access'])->where('uid',$uid)->find();
$title = Db::name($this->config['auth_group'])->where('id',$auth_group_access['group_id'])->value('title');
return $title;
}catch (\Exception $e){
return '此用戶未授予角色';
}
}
/**
* 授予用戶權限
*/
public function setRole($uid,$group_id){
$res = Db::name('auth_group_access')
->where('uid',$uid)
->update(['group_id'=>$group_id]);
return true;
}
}
```
* ## 四.使用
1. 在某個控制的方法里
~~~
// 引入類庫
use lib\Auth;
// 獲取auth實例
//$auth = Auth::instance();
//下面代碼動態判斷權限
$auth = new Auth();
// 檢測權限
if ($auth->check('show_button', 1)) { // 第一個參數是規則名稱, 第二個參數是用戶UID
//有顯示操作按鈕的權限
} else {
//沒有顯示操作按鈕的權限
}
~~~
~~~
//會員信息編輯頁面展示-demo
public function edit(){
$module = strtolower(app('http')->getName()); //應用名
$controller = strtolower(request()->controller()); //控制器名
$action = strtolower(request()->action()); //方法名
// 請求到的規則名 AuthRule Name
$url=$module . '/' . $controller . '/' . $action;
$uid = session('userid'); //用戶iD
//下面代碼動態判斷權限
$auth = new Auth();
if(!$auth->check($url,$uid)){
echo '沒有權限';
}else{
echo '有權限';
//todo...
}
return View::fetch();
}
~~~
2. 公共控制器
```
<?php
namespace app\admin\controller;
use app\BaseController;
use think\facade\View;
use think\facade\Session;
use lib\Auth;
class Common extends BaseController
{
public function initialize()
{
$uid = session('userid');
if(!Session::has('username') || !Session::has('userid')){
return redirect('/admin/login')->send();
exit;
} else {
$auth = new Auth(); //實例化Auth
// 檢測權限
$module = strtolower(app('http')->getName()); //應用名
$controller = strtolower(request()->controller()); //控制器名
$action = strtolower(request()->action()); //方法名
// 請求到的規則名 AuthRule Name
$url=$module . '/' . $controller . '/' . $action;
// dump($url);exit;
if(!$auth->check($url,$uid)){// 第一個參數是規則名稱,第二個參數是用戶UID
echo '<div style="text-align:center;color:red;margin-top:20%;">您沒有權限,請聯系超級管理員</div>';
exit;
}
}
}
}
```
3. 中間件控制
```
<?php
namespace app\admin\middleware;
use think\Request;
use think\facade\Session;
use lib\Auth;
class CheckAdminLgoin
{
public function handle($request, \Closure $next)
{
$module = strtolower(app('http')->getName()); //應用名
$controller = strtolower(request()->controller()); //控制器名
$action = strtolower(request()->action()); //方法名
// 請求到的規則名 AuthRule Name
$url=$module . '/' . $controller . '/' . $action;
$uid = session('userid'); //用戶iD
//登錄驗證
if(!Session::has('username') || !Session::has('userid')){
return redirect('/admin/login');
} else {
//實例化Auth
$auth = new Auth();
// dump($auth);die;
if (!$auth->check($url,$uid)) {
echo '<div style="text-align:center;color:red;margin-top:20%;">您沒有權限,請聯系超級管理員</div>';
exit;
}
}
return $next($request);
}
}
```
- 空白目錄
- 數據表的創建
- auth _rule
- auth_group
- auth_group_access
- 權限示例
- Auth權限菜單
- Auth用戶組權限修改
- Auth用戶規則表
- Auth權限的使用
- 源碼示例
- thinkphp6auth
- 安裝與拓展
- auth
- thinkphp6.0權限擴展
- ThinkPHP3.2.3完整版中對Auth.class.php的使用
- ThinkPHP6.x中對Auth的使用[tp6-auth權限管理]
- Thinkphp6+Auth+LayuiAdmin+authtree權限管理
- 使用phpstudy安裝
- 使用寶塔安裝thinkphp
- thinkphp6 偽靜態配置(nginx和Apache)
- apiadmin安裝教程