No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Auth.php 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Yzncms [ 御宅男工作室 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018 http://yzncms.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: 御宅男 <530765310@qq.com>
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | AUTH类
  13. // +----------------------------------------------------------------------
  14. namespace libs;
  15. use think\Db;
  16. use think\facade\Config;
  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 $_config = [
  42. 'AUTH_ON' => true, // 认证开关
  43. 'AUTH_TYPE' => 1, // 认证方式,1为实时认证;2为登录认证。
  44. 'AUTH_GROUP' => 'auth_group', // 用户组数据表名
  45. 'AUTH_RULE' => 'auth_rule', // 权限规则表
  46. 'AUTH_USER' => 'admin', // 用户信息表
  47. ];
  48. /**
  49. * 类架构函数
  50. * Auth constructor.
  51. */
  52. public function __construct()
  53. {
  54. //可设置配置项 auth, 此配置项为数组。
  55. if ($auth = Config::get('auth')) {
  56. $this->config = array_merge($this->_config, $auth);
  57. }
  58. // 初始化request
  59. $this->request = Request::instance();
  60. }
  61. /**
  62. * 初始化
  63. * @access public
  64. * @param array $options 参数
  65. * @return Auth
  66. */
  67. public static function instance($options = [])
  68. {
  69. if (is_null(self::$instance)) {
  70. self::$instance = new static($options);
  71. }
  72. return self::$instance;
  73. }
  74. /**
  75. * 检查权限
  76. * @param name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
  77. * @param uid int 认证用户的id
  78. * @param string mode 执行check的模式
  79. * @param relation string 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
  80. * @return boolean 通过验证返回true;失败返回false
  81. */
  82. public function check($name, $uid, $mode = 'url', $relation = 'or')
  83. {
  84. if (!$this->_config['AUTH_ON']) {
  85. return true;
  86. }
  87. $authList = $this->getAuthList($uid); //获取用户需要验证的所有有效规则列表
  88. if (in_array('*', $authList)) {
  89. return true;
  90. }
  91. if (is_string($name)) {
  92. $name = strtolower($name);
  93. if (strpos($name, ',') !== false) {
  94. $name = explode(',', $name);
  95. } else {
  96. $name = [$name];
  97. }
  98. }
  99. $list = []; //保存验证通过的规则名
  100. if ('url' == $mode) {
  101. $REQUEST = unserialize(strtolower(serialize($this->request->param())));
  102. }
  103. foreach ($authList as $auth) {
  104. $query = preg_replace('/^.+\?/U', '', $auth);
  105. if ($mode == 'url' && $query != $auth) {
  106. parse_str($query, $param); //解析规则中的param
  107. $intersect = array_intersect_assoc($REQUEST, $param);
  108. $auth = preg_replace('/\?.*$/U', '', $auth);
  109. if (in_array($auth, $name) && $intersect == $param) {
  110. //如果节点相符且url参数满足
  111. $list[] = $auth;
  112. }
  113. } elseif (in_array($auth, $name)) {
  114. $list[] = $auth;
  115. }
  116. }
  117. if ($relation == 'or' and !empty($list)) {
  118. return true;
  119. }
  120. $diff = array_diff($name, $list);
  121. if ($relation == 'and' and empty($diff)) {
  122. return true;
  123. }
  124. return false;
  125. }
  126. /**
  127. * 根据用户id获取用户组,返回值为数组
  128. * @param uid int 用户id
  129. * @return array 用户所属的用户组 array(
  130. * array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
  131. * ...)
  132. */
  133. public function getGroups($uid)
  134. {
  135. static $groups = [];
  136. if (isset($groups[$uid])) {
  137. return $groups[$uid];
  138. }
  139. $user_groups = Db::name($this->_config['AUTH_USER'])
  140. ->alias('a')
  141. ->where('a.id', $uid)
  142. ->where('g.status', 1)
  143. ->join($this->_config['AUTH_GROUP'] . ' g', "g.id = a.roleid")
  144. ->field('a.id as uid,g.id,g.parentid,roleid,title,rules')
  145. ->select();
  146. $groups[$uid] = $user_groups ?: [];
  147. return $groups[$uid];
  148. }
  149. /**
  150. * 获得权限列表
  151. * @param integer $uid 用户id
  152. */
  153. protected function getAuthList($uid)
  154. {
  155. static $_rulelist = []; //保存用户验证通过的权限列表
  156. if (isset($_rulelist[$uid])) {
  157. return $_rulelist[$uid];
  158. }
  159. if (2 == $this->_config['AUTH_TYPE'] && Session::has('_AUTH_LIST_' . $uid)) {
  160. return Session::get('_AUTH_LIST_' . $uid);
  161. }
  162. // 读取用户规则节点
  163. $ids = $this->getRuleIds($uid);
  164. if (empty($ids)) {
  165. $_rulelist[$uid] = [];
  166. return [];
  167. }
  168. $where = [
  169. ['status', '=', 1],
  170. ];
  171. if (!in_array('*', $ids)) {
  172. $where[] = ['id', 'in', $ids];
  173. }
  174. //读取用户组所有权限规则
  175. $rules = Db::name($this->_config['AUTH_RULE'])->where($where)->field('id,parentid,condition,icon,name,title,ismenu')->select();
  176. //循环规则,判断结果。
  177. $rulelist = [];
  178. if (in_array('*', $ids)) {
  179. $rulelist[] = "*";
  180. }
  181. foreach ($rules as $rule) {
  182. //超级管理员无需验证condition
  183. if (!empty($rule['condition']) && !in_array('*', $ids)) {
  184. //根据condition进行验证
  185. $user = $this->getUserInfo($uid); //获取用户信息,一维数组
  186. $nums = 0;
  187. $condition = str_replace(['&&', '||'], "\r\n", $rule['condition']);
  188. $condition = preg_replace('/\{(\w*?)\}/', '\\1', $condition);
  189. $conditionArr = explode("\r\n", $condition);
  190. foreach ($conditionArr as $index => $item) {
  191. preg_match("/^(\w+)\s?([\>\<\=]+)\s?(.*)$/", trim($item), $matches);
  192. if ($matches && isset($user[$matches[1]]) && version_compare($user[$matches[1]], $matches[3], $matches[2])) {
  193. $nums++;
  194. }
  195. }
  196. if ($conditionArr && ((stripos($rule['condition'], "||") !== false && $nums > 0) || count($conditionArr) == $nums)) {
  197. $rulelist[$rule['id']] = strtolower($rule['name']);
  198. }
  199. } else {
  200. //只要存在就记录
  201. $rulelist[$rule['id']] = strtolower($rule['name']);
  202. }
  203. }
  204. $_rulelist[$uid] = $rulelist;
  205. //登录验证则需要保存规则列表
  206. if (2 == $this->_config['AUTH_TYPE']) {
  207. //规则列表结果保存到session
  208. Session::set('_AUTH_LIST_' . $uid, $rulelist);
  209. }
  210. return array_unique($rulelist);
  211. }
  212. public function getRuleIds($uid)
  213. {
  214. //读取用户所属用户组
  215. $groups = $this->getGroups($uid);
  216. $ids = []; //保存用户所属用户组设置的所有权限规则id
  217. foreach ($groups as $g) {
  218. $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
  219. }
  220. $ids = array_unique($ids);
  221. return $ids;
  222. }
  223. /**
  224. * 获得用户资料,根据自己的情况读取数据库
  225. */
  226. protected function getUserInfo($uid)
  227. {
  228. static $userinfo = [];
  229. if (!isset($userinfo[$uid])) {
  230. $userinfo[$uid] = Db::name($this->_config['auth_user'])->where(['id' => $uid])->find();
  231. }
  232. return $userinfo[$uid];
  233. }
  234. }