Auth.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | AUTH类
  13. // +----------------------------------------------------------------------
  14. namespace libs;
  15. use think\facade\Config;
  16. use think\facade\Db;
  17. use think\facade\Request;
  18. use think\facade\Session;
  19. /**
  20. * 权限认证类
  21. * 功能特性:
  22. * 1,是对规则进行认证,不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
  23. * $auth=new Auth(); $auth->check('规则名称','用户id')
  24. * 2,可以同时对多条规则进行认证,并设置多条规则的关系(or或者and)
  25. * $auth=new Auth(); $auth->check('规则1,规则2','用户id','and')
  26. * 第三个参数为and时表示,用户需要同时具有规则1和规则2的权限。 当第三个参数为or时,表示用户值需要具备其中一个条件即可。默认为or
  27. * 3,一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
  28. *
  29. * 4,支持规则表达式。
  30. * 在think_auth_rule 表中定义一条规则时,如果type为1, condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100 表示用户的分数在5-100之间时这条规则才会通过。
  31. */
  32. class Auth
  33. {
  34. protected static $instance;
  35. /**
  36. * 当前请求实例
  37. * @var Request
  38. */
  39. protected $request;
  40. //默认配置
  41. protected array $config = [
  42. 'AUTH_ON' => true, // 认证开关
  43. 'AUTH_TYPE' => 1, // 认证方式,1为实时认证;2为登录认证。
  44. 'AUTH_GROUP' => 'auth_group', // 用户组数据表名
  45. 'AUTH_GROUP_ACCESS' => 'auth_group_access', // 用户-用户组关系表
  46. 'AUTH_RULE' => 'auth_rule', // 权限规则表
  47. 'AUTH_USER' => 'admin', // 用户信息表
  48. ];
  49. /**
  50. * 类架构函数
  51. * Auth constructor.
  52. */
  53. public function __construct()
  54. {
  55. //可设置配置项 auth, 此配置项为数组。
  56. if ($auth = Config::get('auth')) {
  57. $this->config = array_merge($this->config, $auth);
  58. }
  59. // 初始化request
  60. $this->request = Request::instance();
  61. }
  62. /**
  63. * 初始化
  64. * @param array $options 参数
  65. * @return static
  66. */
  67. public static function instance(array $options = [])
  68. {
  69. if (is_null(self::$instance)) {
  70. self::$instance = new static($options);
  71. }
  72. return self::$instance;
  73. }
  74. /**
  75. * 检查权限
  76. * @param array|string $name 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
  77. * @param int $uid 认证用户的id
  78. * @param string $mode 执行check的模式
  79. * @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
  80. * @return bool 通过验证返回true;失败返回false
  81. * @throws \think\db\exception\DataNotFoundException
  82. * @throws \think\db\exception\DbException
  83. * @throws \think\db\exception\ModelNotFoundException
  84. */
  85. public function check(array | string $name, int $uid, string $mode = 'url', string $relation = 'or')
  86. {
  87. if (!$this->config['AUTH_ON']) {
  88. return true;
  89. }
  90. $authList = $this->getAuthList($uid); //获取用户需要验证的所有有效规则列表
  91. if (in_array('*', $authList)) {
  92. return true;
  93. }
  94. if (is_string($name)) {
  95. $name = strtolower($name);
  96. if (str_contains($name, ',')) {
  97. $name = explode(',', $name);
  98. } else {
  99. $name = [$name];
  100. }
  101. }
  102. $list = []; //保存验证通过的规则名
  103. if ('url' == $mode) {
  104. $REQUEST = unserialize(strtolower(serialize($this->request->param())));
  105. }
  106. foreach ($authList as $auth) {
  107. $query = preg_replace('/^.+\?/U', '', $auth);
  108. if ($mode == 'url' && $query != $auth) {
  109. parse_str($query, $param); //解析规则中的param
  110. $intersect = array_intersect_assoc($REQUEST, $param);
  111. $auth = preg_replace('/\?.*$/U', '', $auth);
  112. if (in_array($auth, $name) && $intersect == $param) {
  113. //如果节点相符且url参数满足
  114. $list[] = $auth;
  115. }
  116. } elseif (in_array($auth, $name)) {
  117. $list[] = $auth;
  118. }
  119. }
  120. if ($relation == 'or' and !empty($list)) {
  121. return true;
  122. }
  123. $diff = array_diff($name, $list);
  124. if ($relation == 'and' and empty($diff)) {
  125. return true;
  126. }
  127. return false;
  128. }
  129. /**
  130. * 根据用户id获取用户组,返回值为数组
  131. * @param int $uid 用户id
  132. * @return array|mixed 用户所属的用户组 array(
  133. * array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
  134. * ...)
  135. * @throws \think\db\exception\DataNotFoundException
  136. * @throws \think\db\exception\DbException
  137. * @throws \think\db\exception\ModelNotFoundException
  138. */
  139. public function getGroups(int $uid)
  140. {
  141. static $groups = [];
  142. if (isset($groups[$uid])) {
  143. return $groups[$uid];
  144. }
  145. $user_groups = Db::name($this->config['AUTH_GROUP_ACCESS'])
  146. ->alias('aga')
  147. ->join($this->config['AUTH_GROUP'] . ' ag', 'aga.group_id = ag.id', 'LEFT')
  148. ->field('aga.uid,aga.group_id,ag.id,ag.parentid,ag.title,ag.rules')
  149. ->where('aga.uid', $uid)
  150. ->where('ag.status', 1)
  151. ->select()->toArray();
  152. $groups[$uid] = $user_groups ?: [];
  153. return $groups[$uid];
  154. }
  155. /**
  156. * 获得权限列表
  157. * @param int $uid 用户id
  158. * @return array|mixed
  159. * @throws \think\db\exception\DataNotFoundException
  160. * @throws \think\db\exception\DbException
  161. * @throws \think\db\exception\ModelNotFoundException
  162. */
  163. protected function getAuthList(int $uid)
  164. {
  165. static $_rulelist = []; //保存用户验证通过的权限列表
  166. if (isset($_rulelist[$uid])) {
  167. return $_rulelist[$uid];
  168. }
  169. if (2 == $this->config['AUTH_TYPE'] && Session::has('_AUTH_LIST_' . $uid)) {
  170. return Session::get('_AUTH_LIST_' . $uid);
  171. }
  172. // 读取用户规则节点
  173. $ids = $this->getRuleIds($uid);
  174. if (empty($ids)) {
  175. $_rulelist[$uid] = [];
  176. return [];
  177. }
  178. $where = [
  179. ['status', '=', 1],
  180. ];
  181. if (!in_array('*', $ids)) {
  182. $where[] = ['id', 'in', $ids];
  183. }
  184. //读取用户组所有权限规则
  185. $rules = Db::name($this->config['AUTH_RULE'])->where($where)->field('id,parentid,condition,icon,name,title,ismenu')->select();
  186. //循环规则,判断结果。
  187. $rulelist = [];
  188. if (in_array('*', $ids)) {
  189. $rulelist[] = "*";
  190. }
  191. foreach ($rules as $rule) {
  192. //超级管理员无需验证condition
  193. if (!empty($rule['condition']) && !in_array('*', $ids)) {
  194. //根据condition进行验证
  195. $user = $this->getUserInfo($uid); //获取用户信息,一维数组
  196. $nums = 0;
  197. $condition = str_replace(['&&', '||'], "\r\n", $rule['condition']);
  198. $condition = preg_replace('/\{(\w*?)\}/', '\\1', $condition);
  199. $conditionArr = explode("\r\n", $condition);
  200. foreach ($conditionArr as $index => $item) {
  201. preg_match("/^(\w+)\s?([\>\<\=]+)\s?(.*)$/", trim($item), $matches);
  202. if ($matches && isset($user[$matches[1]]) && version_compare($user[$matches[1]], $matches[3], $matches[2])) {
  203. $nums++;
  204. }
  205. }
  206. if ($conditionArr && ((stripos($rule['condition'], "||") !== false && $nums > 0) || count($conditionArr) == $nums)) {
  207. $rulelist[$rule['id']] = strtolower($rule['name']);
  208. }
  209. } else {
  210. //只要存在就记录
  211. $rulelist[$rule['id']] = strtolower($rule['name']);
  212. }
  213. }
  214. $_rulelist[$uid] = $rulelist;
  215. //登录验证则需要保存规则列表
  216. if (2 == $this->config['AUTH_TYPE']) {
  217. //规则列表结果保存到session
  218. Session::set('_AUTH_LIST_' . $uid, $rulelist);
  219. }
  220. return array_unique($rulelist);
  221. }
  222. public function getRuleIds(int $uid)
  223. {
  224. //读取用户所属用户组
  225. $groups = $this->getGroups($uid);
  226. $ids = []; //保存用户所属用户组设置的所有权限规则id
  227. foreach ($groups as $g) {
  228. $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
  229. }
  230. return array_unique($ids);
  231. }
  232. /**
  233. * 获得用户资料,根据自己的情况读取数据库
  234. */
  235. protected function getUserInfo(int $uid)
  236. {
  237. static $userinfo = [];
  238. if (!isset($userinfo[$uid])) {
  239. $userinfo[$uid] = Db::name($this->config['AUTH_USER'])->find($uid);
  240. }
  241. return $userinfo[$uid];
  242. }
  243. }