refactor:权限规则类兼容常驻内存运行

This commit is contained in:
妙码生花 2024-03-11 22:02:35 +08:00
parent 631fccd9e6
commit ca04172291

View File

@ -6,14 +6,14 @@ use Throwable;
use think\facade\Db; use think\facade\Db;
/** /**
* 权限规则检测 * 权限规则
*/ */
class Auth class Auth
{ {
/** /**
* 用户有权限的规则节点 * 用户有权限的规则节点
*/ */
protected array $rules = []; protected static array $rules = [];
/** /**
* 默认配置 * 默认配置
@ -59,19 +59,18 @@ class Auth
*/ */
public function getMenus(int $uid): array public function getMenus(int $uid): array
{ {
if (!$this->rules) { if (empty(self::$rules[$uid])) {
$this->getRuleList($uid); $this->getRuleList($uid);
} }
if (!$this->rules) return []; if (empty(self::$rules[$uid])) return [];
foreach ($this->rules as $rule) { $this->children = [];
foreach (self::$rules[$uid] as $rule) {
$this->children[$rule['pid']][] = $rule; $this->children[$rule['pid']][] = $rule;
} }
// 没有根菜单规则 // 没有根菜单规则
if (!isset($this->children[0])) { if (!isset($this->children[0])) return [];
return [];
}
return $this->getChildren($this->children[0]); return $this->getChildren($this->children[0]);
} }
@ -155,44 +154,38 @@ class Auth
*/ */
public function getRuleList(int $uid): array public function getRuleList(int $uid): array
{ {
// 静态保存所有用户验证通过的权限列表
static $ruleList = [];
if (isset($ruleList[$uid])) {
return $ruleList[$uid];
}
// 读取用户规则节点 // 读取用户规则节点
$ids = $this->getRuleIds($uid); $ids = $this->getRuleIds($uid);
if (empty($ids)) { if (empty($ids)) return [];
$ruleList[$uid] = [];
return [];
}
// 读取用户所有权限规则
if (empty(self::$rules[$uid])) {
$where = [];
$where[] = ['status', '=', '1']; $where[] = ['status', '=', '1'];
// 如果没有 * 则只获取用户拥有的规则 // 如果没有 * 则只获取用户拥有的规则
if (!in_array('*', $ids)) { if (!in_array('*', $ids)) {
$where[] = ['id', 'in', $ids]; $where[] = ['id', 'in', $ids];
} }
// 读取用户组所有权限规则 self::$rules[$uid] = Db::name($this->config['auth_rule'])
$this->rules = Db::name($this->config['auth_rule'])
->withoutField(['remark', 'status', 'weigh', 'update_time', 'create_time']) ->withoutField(['remark', 'status', 'weigh', 'update_time', 'create_time'])
->where($where) ->where($where)
->order('weigh desc,id asc') ->order('weigh desc,id asc')
->select() ->select()
->toArray(); ->toArray();
foreach (self::$rules[$uid] as $key => $rule) {
if (!empty($rule['keepalive'])) self::$rules[$uid][$key]['keepalive'] = $rule['name'];
}
}
// 用户规则 // 用户规则
$rules = []; $rules = [];
if (in_array('*', $ids)) { if (in_array('*', $ids)) {
$rules[] = "*"; $rules[] = "*";
} }
foreach ($this->rules as $key => $rule) { foreach (self::$rules[$uid] as $rule) {
$rules[$rule['id']] = strtolower($rule['name']); $rules[$rule['id']] = strtolower($rule['name']);
if (isset($rule['keepalive']) && $rule['keepalive']) {
$this->rules[$key]['keepalive'] = $rule['name'];
} }
}
$ruleList[$uid] = $rules;
return array_unique($rules); return array_unique($rules);
} }