## auth 權限控制類
~~~
<?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\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,一個用戶可以屬于多個用戶組(think_auth_group_access表 定義了用戶所屬用戶組)。我們需要設置每個用戶組擁有哪些規則(think_auth_group 定義了用戶組權限)
* 4,支持規則表達式。
* 在think_auth_rule 表中定義一條規則,condition字段就可以定義規則表達式。 如定義{score}>5 and {score}<100
* 表示用戶的分數在5-100之間時這條規則才會通過。
*/
class Auth
{
/**
* @var object 對象實例
*/
protected static $instance;
protected $rules = [];
/**
* 當前請求實例
* @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' => 'user', // 用戶信息表
];
public function __construct()
{
if ($auth = config('auth.auth')) {
$this->config = array_merge($this->config, $auth);
}
// 初始化request
$this->request = Request::instance();
}
/**
* 初始化
* @access public
* @param array $options 參數
* @return Auth
*/
public static function instance($options = [])
{
if (is_null(self::$instance)) {
self::$instance = new static($options);
}
return self::$instance;
}
/**
* 檢查權限
* @param string|array $name 需要驗證的規則列表,支持逗號分隔的權限規則或索引數組
* @param int $uid 認證用戶的id
* @param string $relation 如果為 'or' 表示滿足任一條規則即通過驗證;如果為 'and'則表示需滿足所有規則才能通過驗證
* @param string $mode 執行驗證的模式,可分為url,normal
* @return bool 通過驗證返回true;失敗返回false
*/
public function check($name, $uid, $relation = 'or', $mode = 'url')
{
if (!$this->config['auth_on']) {
return true;
}
// 獲取用戶需要驗證的所有有效規則列表
$rulelist = $this->getRuleList($uid);
if (in_array('*', $rulelist)) {
return true;
}
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 ($rulelist as $rule) {
$query = preg_replace('/^.+\?/U', '', $rule);
if ('url' == $mode && $query != $rule) {
parse_str($query, $param); //解析規則中的param
$intersect = array_intersect_assoc($REQUEST, $param);
$rule = preg_replace('/\?.*$/U', '', $rule);
if (in_array($rule, $name) && $intersect == $param) {
//如果節點相符且url參數滿足
$list[] = $rule;
}
} else {
if (in_array($rule, $name)) {
$list[] = $rule;
}
}
}
if ('or' == $relation && !empty($list)) {
return true;
}
$diff = array_diff($name, $list);
if ('and' == $relation && empty($diff)) {
return true;
}
return false;
}
/**
* 根據用戶id獲取用戶組,返回值為數組
* @param int $uid 用戶id
* @return array 用戶所屬的用戶組 array(
* array('uid'=>'用戶id','group_id'=>'用戶組id','name'=>'用戶組名稱','rules'=>'用戶組擁有的規則id,多個,號隔開'),
* ...)
*/
public function getGroups($uid)
{
static $groups = [];
if (isset($groups[$uid])) {
return $groups[$uid];
}
// 執行查詢
$user_groups = Db::name($this->config['auth_group_access'])
->alias('aga')
->join('__' . strtoupper($this->config['auth_group']) . '__ ag', 'aga.group_id = ag.id', 'LEFT')
->field('aga.uid,aga.group_id,ag.id,ag.pid,ag.name,ag.rules')
->where("aga.uid='{$uid}' and ag.status='normal'")
->select();
$groups[$uid] = $user_groups ?: [];
return $groups[$uid];
}
/**
* 獲得權限規則列表
* @param int $uid 用戶id
* @return array
*/
public function getRuleList($uid)
{
static $_rulelist = []; //保存用戶驗證通過的權限列表
if (isset($_rulelist[$uid])) {
return $_rulelist[$uid];
}
if (2 == $this->config['auth_type'] && Session::has('_rule_list_' . $uid)) {
return Session::get('_rule_list_' . $uid);
}
// 讀取用戶規則節點
$ids = $this->getRuleIds($uid);
if (empty($ids)) {
$_rulelist[$uid] = [];
return [];
}
// 篩選條件
/*$where = [
'status' => 'normal'
];
if (!in_array('*', $ids)) {
$ids = ['in', $ids];
}*/
if (!in_array('*', $ids)) {
$where =['status' => 'normal','id'=>$ids];
}else{
$where =['status' => 'normal'];
}
//讀取用戶組所有權限規則
$this->rules = Db::name($this->config['auth_rule'])->where($where)->select();
//循環規則,判斷結果。
$rulelist = []; //
if (in_array('*', $ids)) {
$rulelist[] = "*";
}
foreach ($this->rules as $rule) {
//超級管理員無需驗證condition
if (!empty($rule['condition']) && !in_array('*', $ids)) {
//根據condition進行驗證
$user = $this->getUserInfo($uid); //獲取用戶信息,一維數組
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
@(eval('$condition=(' . $command . ');'));
if ($condition) {
$rulelist[$rule['id']] = strtolower($rule['name']);
}
} else {
//只要存在就記錄
$rulelist[$rule['id']] = strtolower($rule['name']);
}
}
$_rulelist[$uid] = $rulelist;
//登錄驗證則需要保存規則列表
if (2 == $this->config['auth_type']) {
//規則列表結果保存到session
Session::set('_rule_list_' . $uid, $rulelist);
}
return array_unique($rulelist);
}
public function getRuleIds($uid)
{
//讀取用戶所屬用戶組
$groups = $this->getGroups($uid);
$ids = []; //保存用戶所屬用戶組設置的所有權限規則id
foreach ($groups as $g) {
$ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
}
$ids = array_unique($ids);
return $ids;
}
/**
* 獲得用戶資料
* @param int $uid 用戶id
* @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];
}
}
~~~
- thinkphp
- thinkphp筆記
- 后臺登陸退出
- config配置
- 隱藏后臺模塊
- 單獨調用騰訊云行為驗證碼
- api接口跨域問題
- api接口創建案例代碼
- 使用gateway worker
- 使用swoole代碼筆記
- 使用隊列 think-queue筆記
- 后臺布局
- MySQL
- 1、關于lnmp mysql的一個坑
- 2、mysql實現group by后取各分組的最新一條
- 其他
- 搞笑的注釋代碼
- 分頁類
- nodejs 打包網址為exe
- 免費天氣預報API接口
- Ajax
- 簡單的ajax分頁1
- 通用ajax-post提交
- 引用的類庫文件
- Auth.php
- Auth.php權限控制對應的數據庫表結構
- Layui.php
- Pinyin.php
- Random.php
- Tree.php
- Tree2.php
- Js-Jq
- Git的使用
- 3、bootstrap-datetimepicker實現兩個時間范圍輸入
- CentOS安裝SSR做梯子
- Python爬蟲
- 1、安裝Gerapy
- 2、安裝Scrapy
- 3、Scrapy使用
- 4、Scrapy框架,爬取網站返回json數據(spider源碼)
- 0、Python pip更換國內源(一句命令換源)
- 服務器運維
- 1、寶塔使用webhook更新服務器代碼
- 2、搭建內網穿透
- 3、數據庫主從同步
- 4、數據庫復制
- hui-Shop問題
- 1、前端模板的注意事項
- 2、模板標簽