Auth.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <?php
  2. namespace ba;
  3. use Throwable;
  4. use think\facade\Db;
  5. /**
  6. * 权限规则类
  7. */
  8. class Auth
  9. {
  10. /**
  11. * 默认配置
  12. * @var array|string[]
  13. */
  14. protected array $config = [
  15. 'auth_group' => 'admin_group', // 用户组数据表名
  16. 'auth_group_access' => 'admin_group_access', // 用户-用户组关系表
  17. 'auth_rule' => 'admin_rule', // 权限规则表
  18. ];
  19. /**
  20. * 子菜单规则数组
  21. * @var array
  22. */
  23. protected array $children = [];
  24. /**
  25. * 构造方法
  26. * @param array $config
  27. */
  28. public function __construct(array $config = [])
  29. {
  30. $this->config = array_merge($this->config, $config);
  31. }
  32. /**
  33. * 魔术方法-获取当前配置
  34. * @param $name
  35. * @return mixed
  36. */
  37. public function __get($name): mixed
  38. {
  39. return $this->config[$name];
  40. }
  41. /**
  42. * 获取菜单规则列表
  43. * @access public
  44. * @param int $uid 用户ID
  45. * @return array
  46. * @throws Throwable
  47. */
  48. public function getMenus(int $uid): array
  49. {
  50. $this->children = [];
  51. $originAuthRules = $this->getOriginAuthRules($uid);
  52. foreach ($originAuthRules as $rule) {
  53. $this->children[$rule['pid']][] = $rule;
  54. }
  55. // 没有根菜单规则
  56. if (!isset($this->children[0])) return [];
  57. return $this->getChildren($this->children[0]);
  58. }
  59. /**
  60. * 获取传递的菜单规则的子规则
  61. * @param array $rules 菜单规则
  62. * @return array
  63. */
  64. private function getChildren(array $rules): array
  65. {
  66. foreach ($rules as $key => $rule) {
  67. if (array_key_exists($rule['id'], $this->children)) {
  68. $rules[$key]['children'] = $this->getChildren($this->children[$rule['id']]);
  69. }
  70. }
  71. return $rules;
  72. }
  73. /**
  74. * 检查是否有某权限
  75. * @param string $name 菜单规则的 name,可以传递两个,以','号隔开
  76. * @param int $uid 用户ID
  77. * @param string $relation 如果出现两个 name,是两个都通过(and)还是一个通过即可(or)
  78. * @param string $mode 如果不使用 url 则菜单规则name匹配到即通过
  79. * @return bool
  80. * @throws Throwable
  81. */
  82. public function check(string $name, int $uid, string $relation = 'or', string $mode = 'url'): bool
  83. {
  84. // 获取用户需要验证的所有有效规则列表
  85. $ruleList = $this->getRuleList($uid);
  86. if (in_array('*', $ruleList)) {
  87. return true;
  88. }
  89. if ($name) {
  90. $name = strtolower($name);
  91. if (str_contains($name, ',')) {
  92. $name = explode(',', $name);
  93. } else {
  94. $name = [$name];
  95. }
  96. }
  97. $list = []; //保存验证通过的规则名
  98. if ('url' == $mode) {
  99. $REQUEST = json_decode(strtolower(json_encode(request()->param(), JSON_UNESCAPED_UNICODE)), true);
  100. }
  101. foreach ($ruleList as $rule) {
  102. $query = preg_replace('/^.+\?/U', '', $rule);
  103. if ('url' == $mode && $query != $rule) {
  104. parse_str($query, $param); //解析规则中的param
  105. $intersect = array_intersect_assoc($REQUEST, $param);
  106. $rule = preg_replace('/\?.*$/U', '', $rule);
  107. if (in_array($rule, $name) && $intersect == $param) {
  108. // 如果节点相符且url参数满足
  109. $list[] = $rule;
  110. }
  111. } elseif (in_array($rule, $name)) {
  112. $list[] = $rule;
  113. }
  114. }
  115. if ('or' == $relation && !empty($list)) {
  116. return true;
  117. }
  118. $diff = array_diff($name, $list);
  119. if ('and' == $relation && empty($diff)) {
  120. return true;
  121. }
  122. return false;
  123. }
  124. /**
  125. * 获得权限规则列表
  126. * @param int $uid 用户id
  127. * @return array
  128. * @throws Throwable
  129. */
  130. public function getRuleList(int $uid): array
  131. {
  132. // 读取用户规则节点
  133. $ids = $this->getRuleIds($uid);
  134. if (empty($ids)) return [];
  135. $originAuthRules = $this->getOriginAuthRules($uid);
  136. // 用户规则
  137. $rules = [];
  138. if (in_array('*', $ids)) {
  139. $rules[] = "*";
  140. }
  141. foreach ($originAuthRules as $rule) {
  142. $rules[$rule['id']] = strtolower($rule['name']);
  143. }
  144. return array_unique($rules);
  145. }
  146. /**
  147. * 获得权限规则原始数据
  148. * @param int $uid 用户id
  149. * @return array
  150. * @throws Throwable
  151. */
  152. public function getOriginAuthRules(int $uid): array
  153. {
  154. $ids = $this->getRuleIds($uid);
  155. if (empty($ids)) return [];
  156. $where = [];
  157. $where[] = ['status', '=', '1'];
  158. // 如果没有 * 则只获取用户拥有的规则
  159. if (!in_array('*', $ids)) {
  160. $where[] = ['id', 'in', $ids];
  161. }
  162. $rules = Db::name($this->config['auth_rule'])
  163. ->withoutField(['remark', 'status', 'weigh', 'update_time', 'create_time'])
  164. ->where($where)
  165. ->order('weigh desc,id asc')
  166. ->select()
  167. ->toArray();
  168. foreach ($rules as $key => $rule) {
  169. if (!empty($rule['keepalive'])) {
  170. $rules[$key]['keepalive'] = $rule['name'];
  171. }
  172. }
  173. return $rules;
  174. }
  175. /**
  176. * 获取权限规则ids
  177. * @param int $uid
  178. * @return array
  179. * @throws Throwable
  180. */
  181. public function getRuleIds(int $uid): array
  182. {
  183. // 用户的组别和规则ID
  184. $groups = $this->getGroups($uid);
  185. $ids = [];
  186. foreach ($groups as $g) {
  187. $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
  188. }
  189. return array_unique($ids);
  190. }
  191. /**
  192. * 获取用户所有分组和对应权限规则
  193. * @param int $uid
  194. * @return array
  195. * @throws Throwable
  196. */
  197. public function getGroups(int $uid): array
  198. {
  199. $dbName = $this->config['auth_group_access'] ?: 'user';
  200. if ($this->config['auth_group_access']) {
  201. $userGroups = Db::name($dbName)
  202. ->alias('aga')
  203. ->join($this->config['auth_group'] . ' ag', 'aga.group_id = ag.id', 'LEFT')
  204. ->field('aga.uid,aga.group_id,ag.id,ag.pid,ag.name,ag.rules')
  205. ->where("aga.uid='$uid' and ag.status='1'")
  206. ->select()
  207. ->toArray();
  208. } else {
  209. $userGroups = Db::name($dbName)
  210. ->alias('u')
  211. ->join($this->config['auth_group'] . ' ag', 'u.group_id = ag.id', 'LEFT')
  212. ->field('u.id as uid,u.group_id,ag.id,ag.name,ag.rules')
  213. ->where("u.id='$uid' and ag.status='1'")
  214. ->select()
  215. ->toArray();
  216. }
  217. return $userGroups;
  218. }
  219. }