~~~
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614>
// +----------------------------------------------------------------------
// | 修改者: anuo (本權限類在原3.2.3的基礎上修改過來的)
// +----------------------------------------------------------------------
namespace lib;
use think\Db;
use think\Config;
use think\Session;
use think\Request;
use think\Loader;
/**
* 權限認證類
* 功能特性:
* 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,一個用戶可以屬于多個用戶組(think_auth_group_access表 定義了用戶所屬用戶組)。我們需要設置每個用戶組擁有哪些規則(think_auth_group 定義了用戶組權限)
* 4,支持規則表達式。
* 在think_auth_rule 表中定義一條規則時,如果type為1, condition字段就可以定義規則表達式。 如定義{score}>5 and {score}<100
* 表示用戶的分數在5-100之間時這條規則才會通過。
*/
//數據庫
/*
-- ----------------------------
-- think_auth_rule,規則表,
-- id:主鍵,name:規則唯一標識, title:規則中文名稱 status 狀態:為1正常,為0禁用,condition:規則表達式,為空表示存在就驗證,不為空表示按照條件驗證
-- ----------------------------
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 '',
`type` tinyint(1) NOT NULL DEFAULT '1',
`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;
-- ----------------------------
-- think_auth_group 用戶組表,
-- id:主鍵, title:用戶組中文名稱, rules:用戶組擁有的規則id, 多個規則","隔開,status 狀態:為1正常,為0禁用
-- ----------------------------
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;
-- ----------------------------
-- think_auth_group_access 用戶組明細表
-- uid:用戶id,group_id:用戶組id
-- ----------------------------
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;
*/
class Auth
{
/**
* @var object 對象實例
*/
protected static $instance;
/**
* 當前請求實例
* @var Request
*/
protected $request;
//默認配置
protected $config = [
'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', // 用戶信息表
];
/**
* 類架構函數
* Auth constructor.
*/
public function __construct()
{
//可設置配置項 auth, 此配置項為數組。
if ($auth = Config::get('auth')) {
$this->config = array_merge($this->config, $auth);
}
// 初始化request
$this->request = Request::instance();
}
/**
* 初始化
* @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);
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($this->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;
}
}
}
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 = Loader::parseName($this->config['auth_group_access'], 1);
$auth_group = Loader::parseName($this->config['auth_group'], 1);
// 執行查詢
$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 = [
'id' => ['in', $ids],
'type' => $type
];
//讀取用戶組所有權限規則
$rules = Db::name($this->config['auth_rule'])->where($map)->field('condition,name')->select();
//循環規則,判斷結果。
$authList = []; //
foreach ($rules as $rule) {
if (!empty($rule['condition'])) {
//根據condition進行驗證
$user = $this->getUserInfo($uid); //獲取用戶信息,一維數組
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
@(eval('$condition=(' . $command . ');'));
if ($condition) {
$authList[] = strtolower($rule['name']);
}
} else {
//只要存在就記錄
$authList[] = strtolower($rule['name']);
}
}
$_authList[$uid . $t] = $authList;
if (2 == $this->config['auth_type']) {
//規則列表結果保存到session
Session::set('_auth_list_' . $uid . $t, $authList);
}
return array_unique($authList);
}
/**
* 獲得用戶資料
* @param $uid
* @return mixed
*/
protected function getUserInfo($uid)
{
static $user_info = [];
$user = Db::name($this->config['auth_user']);
// 獲取用戶表主鍵
$_pk = is_string($user->getPk()) ? $user->getPk() : 'uid';
if (!isset($user_info[$uid])) {
$user_info[$uid] = $user->where($_pk, $uid)->find();
}
return $user_info[$uid];
}
}
~~~
- 空白目錄
- thinkcmf的權限管理
- thinkcmf+unicmf添加頁面
- Thinkphp5做后臺 Uni-app做前臺解決跨域問題
- 組件
- h5跨域-uniapp
- thinkphp5 auth 教程
- thinkphp5Auth類
- uniapp添加與編輯的差別
- 常見的請求方式
- uni 單選回顯數據_uniapp 頁面跳轉傳值和接收
- uni-app 單選/多選/滑動 demo
- 關于uniapp checkbox多選框如何傳值傳數據
- uniApp 多選框checkbox ,判斷是否選中
- uniapp添加復選框和獲取復選框的值
- uni-app中全選多選單選
- uniapp多選框CheckBox 數據接收
- uniapp下拉列表單選框復選框實戰demo(編輯或詳情頁)
- uni-data-CheckBox-OK
- js 字符串數組轉換成數字數組
- js把字符串轉為數組對象
- js中數組對象字符串的相互轉換
- JS怎么把字符串數組轉換成整型數組
- 小程序開發
- tp5.1跨域請求
- uniapp-h5跨域
- 新增
- order
- uni-app中調取接口的三種方式與封裝uni.request()
- uView-checkbox
- 給u-view的u-select賦值
- uView-下拉框、復選框、單選框 數據發送及接收
- CURD操作
- thinkphp5.1增刪改查
- TP5.1添加數據成功之后返回自增主鍵id
- Thinkphp實戰之Request默認值except only 以及過濾參
- uni-app跨域解決方案
- thinkphp5.1+uni-app接口開發中跨域問題解決方案
- tp6 + uniapp 前后端跨域解決方案
- uniapp-token相關
- uniapp request請求封裝包含token兼容多端,簡單易用
- CORS.php
- ThinkPHP6 API開發前后端分離用戶信息保存在后端的方法
- thinkphp的jwt(JSON Web Token)身份驗證
- thinkphp6增刪改查
- PHP模擬GET,POST請求
- php模擬get、post發送請求的6種方法
- thinkphp6
- uniapp封裝網絡請求
- thinkphp6搭建后端api接口jwt-auth
- uniapp實現APP微信登錄流程
- [uni-app] 中保持用戶登錄狀態
- 詳解vue中localStorage的使用方法
- vue 實現通過vuex 存儲值 在不同界面使用
- dispatch:異步操作,數據提交至 actions ,可用于向后臺提交數據
- ThinkPHP6.0 + Vue + ElementUI + axios 的環境安裝到實現 CURD 操作
- tp6錯誤集
- TP6 模型插入/添加數據,自動插入時間(自動時間戳)
- 手機不開機維修思路
- thinkphp6解決vue跨域問題
- 從0基礎獲取短視頻去水印解析接口制作
- thinkphp5 刪除緩存
- thinkPHP,怎么把json文件里面的數據導入數據庫
- 數字轉字符php
- php – 直接用curl下載遠程文件
- thinkphp – 直接用curl下載遠程文件
- apiAdmin安裝
- echart
- thinkphp開發小程序推廣分享帶參數二維碼生成
- php同比增加函數
- PHP獲取同比上周、上一個月,上一個季度,去年時間區間
- “前3秒”金句100例,趕緊收藏起來!
- PHP配合微信公眾號生成推廣二維碼
- thinkphp5+php微信公眾號二維碼掃碼關注推廣二維碼事件實現
- 獲取當前時間上一周的開始時間和結束時間
- TP6 查找指定工作日
- PHP 獲取當天、近一周、本周、上月、本月、本季度、上季度時間方法大全
- php獲取今日、昨日、本周、本月 日期方法
- Tp5+mysql按年季度月周日小時查詢時無數據的時間段補0方法
- mysql按天統計的時候,該天沒有數據也要統計為0
- 列出一星期的日期 無數據補0
- thinkphp6本周 上周 周一 周末日期
- 補全日期 無數據補0
- php+pv統計代碼實現,Laravel 10 行代碼實現簡單的網站 pv uv 統計
- 通過API獲取ip地址以及城市和運營商
- 獲取訪客信息
- 13行代碼實現微信小程序設置概率觸發激勵視頻閱讀文章
- uniapp 微信小程序 獲取場景值和場景值個性化參數
- 微信小程序分享小程序碼的生成(帶參數)以及參數的獲取
- 小程序推廣分享帶參數二維碼生成
- uniapp微信小程序生成對應頁面二維碼
- uniapp獲取當前頁面url
- uniapp微信小程序--微信登錄
- 微信小程序,生成小程序碼中scene參數的存放和獲取問題
- uni-app 微信小程序生成二維碼帶參數
- uni-app 微信小程序如何把圖片保存到本地相冊?
- thinkPHP5使用assign()傳遞富文本,前端解析成HTML標簽
- tp6解析編輯器里面的html標簽原樣輸出
- PHP判斷url鏈接是否被百度收錄
- 微擎安裝模塊時提示 Failed to connect to we7.rewlkj.com port 80: Timed out
- 小程序碼生成
- thinkphp開發小程序推廣分享帶參數二維碼生成0
- tp3.2偽靜態
- apiadmin安裝教程-2022.8更新
- autojs事件代碼
- uuuu
- thinkphp6: API 多版本控制