Auth.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: luofei614 <weibo.com/luofei614>
  10. // +----------------------------------------------------------------------
  11. // | 修改者: anuo (本权限类在原3.2.3的基础上修改过来的)
  12. // +----------------------------------------------------------------------
  13. namespace fast;
  14. use think\Db;
  15. use think\Config;
  16. use think\Session;
  17. use think\Request;
  18. use think\Loader;
  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. * 4,支持规则表达式。
  29. * 在think_auth_rule 表中定义一条规则,condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100
  30. * 表示用户的分数在5-100之间时这条规则才会通过。
  31. */
  32. class Auth
  33. {
  34. /**
  35. * @var object 对象实例
  36. */
  37. protected static $instance;
  38. protected $rules = [];
  39. /**
  40. * 当前请求实例
  41. * @var Request
  42. */
  43. protected $request;
  44. //默认配置
  45. protected $config = [
  46. 'auth_on' => 1, // 权限开关
  47. 'auth_type' => 1, // 认证方式,1为实时认证;2为登录认证。
  48. 'auth_group' => 'auth_group', // 用户组数据表名
  49. 'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
  50. 'auth_rule' => 'auth_rule', // 权限规则表
  51. 'auth_user' => 'user', // 用户信息表
  52. ];
  53. /**
  54. * 类架构函数
  55. * Auth constructor.
  56. */
  57. public function __construct()
  58. {
  59. if ($auth = Config::get('auth'))
  60. {
  61. $this->config = array_merge($this->config, $auth);
  62. }
  63. // 初始化request
  64. $this->request = Request::instance();
  65. }
  66. /**
  67. * 初始化
  68. * @access public
  69. * @param array $options 参数
  70. * @return Auth
  71. */
  72. public static function instance($options = [])
  73. {
  74. if (is_null(self::$instance))
  75. {
  76. self::$instance = new static($options);
  77. }
  78. return self::$instance;
  79. }
  80. /**
  81. * 检查权限
  82. * @param $name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
  83. * @param $uid int 认证用户的id
  84. * @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
  85. * @param string $mode 执行验证的模式,可分为url,normal
  86. * @return bool 通过验证返回true;失败返回false
  87. */
  88. public function check($name, $uid, $relation = 'or', $mode = 'url')
  89. {
  90. if (!$this->config['auth_on'])
  91. {
  92. return true;
  93. }
  94. // 获取用户需要验证的所有有效规则列表
  95. $rulelist = $this->getRuleList($uid);
  96. if (in_array('*', $rulelist))
  97. return true;
  98. if (is_string($name))
  99. {
  100. $name = strtolower($name);
  101. if (strpos($name, ',') !== false)
  102. {
  103. $name = explode(',', $name);
  104. }
  105. else
  106. {
  107. $name = [$name];
  108. }
  109. }
  110. $list = []; //保存验证通过的规则名
  111. if ('url' == $mode)
  112. {
  113. $REQUEST = unserialize(strtolower(serialize($this->request->param())));
  114. }
  115. foreach ($rulelist as $rule)
  116. {
  117. $query = preg_replace('/^.+\?/U', '', $rule);
  118. if ('url' == $mode && $query != $rule)
  119. {
  120. parse_str($query, $param); //解析规则中的param
  121. $intersect = array_intersect_assoc($REQUEST, $param);
  122. $rule = preg_replace('/\?.*$/U', '', $rule);
  123. if (in_array($rule, $name) && $intersect == $param)
  124. {
  125. //如果节点相符且url参数满足
  126. $list[] = $rule;
  127. }
  128. }
  129. else
  130. {
  131. if (in_array($rule, $name))
  132. {
  133. $list[] = $rule;
  134. }
  135. }
  136. }
  137. if ('or' == $relation && !empty($list))
  138. {
  139. return true;
  140. }
  141. $diff = array_diff($name, $list);
  142. if ('and' == $relation && empty($diff))
  143. {
  144. return true;
  145. }
  146. return false;
  147. }
  148. /**
  149. * 根据用户id获取用户组,返回值为数组
  150. * @param $uid int 用户id
  151. * @return array 用户所属的用户组 array(
  152. * array('uid'=>'用户id','group_id'=>'用户组id','name'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
  153. * ...)
  154. */
  155. public function getGroups($uid)
  156. {
  157. static $groups = [];
  158. if (isset($groups[$uid]))
  159. {
  160. return $groups[$uid];
  161. }
  162. // 执行查询
  163. $user_groups = Db::name($this->config['auth_group_access'])
  164. ->alias('aga')
  165. ->join('__' . strtoupper($this->config['auth_group']) . '__ ag', 'aga.group_id = ag.id', 'LEFT')
  166. ->field('aga.uid,aga.group_id,ag.id,ag.pid,ag.name,ag.rules')
  167. ->where("aga.uid='{$uid}' and ag.status='normal'")
  168. ->select();
  169. $groups[$uid] = $user_groups ?: [];
  170. return $groups[$uid];
  171. }
  172. /**
  173. * 获得权限规则列表
  174. * @param integer $uid 用户id
  175. * @return array
  176. */
  177. public function getRuleList($uid)
  178. {
  179. static $_rulelist = []; //保存用户验证通过的权限列表
  180. if (isset($_rulelist[$uid]))
  181. {
  182. return $_rulelist[$uid];
  183. }
  184. if (2 == $this->config['auth_type'] && Session::has('_rule_list_' . $uid))
  185. {
  186. return Session::get('_rule_list_' . $uid);
  187. }
  188. // 读取用户规则节点
  189. $ids = $this->getRuleIds($uid);
  190. if (empty($ids))
  191. {
  192. $_rulelist[$uid] = [];
  193. return [];
  194. }
  195. // 筛选条件
  196. $where = [
  197. 'status' => 'normal'
  198. ];
  199. if (!in_array('*', $ids))
  200. {
  201. $where['id'] = ['in', $ids];
  202. }
  203. //读取用户组所有权限规则
  204. $this->rules = Db::name($this->config['auth_rule'])->where($where)->field('id,pid,condition,icon,name,title,ismenu')->select();
  205. //循环规则,判断结果。
  206. $rulelist = []; //
  207. if (in_array('*', $ids))
  208. {
  209. $rulelist[] = "*";
  210. }
  211. foreach ($this->rules as $rule)
  212. {
  213. //超级管理员无需验证condition
  214. if (!empty($rule['condition']) && !in_array('*', $ids))
  215. {
  216. //根据condition进行验证
  217. $user = $this->getUserInfo($uid); //获取用户信息,一维数组
  218. $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
  219. @(eval('$condition=(' . $command . ');'));
  220. if ($condition)
  221. {
  222. $rulelist[$rule['id']] = strtolower($rule['name']);
  223. }
  224. }
  225. else
  226. {
  227. //只要存在就记录
  228. $rulelist[$rule['id']] = strtolower($rule['name']);
  229. }
  230. }
  231. $_rulelist[$uid] = $rulelist;
  232. //登录验证则需要保存规则列表
  233. if (2 == $this->config['auth_type'])
  234. {
  235. //规则列表结果保存到session
  236. Session::set('_rule_list_' . $uid, $rulelist);
  237. }
  238. return array_unique($rulelist);
  239. }
  240. public function getRuleIds($uid)
  241. {
  242. //读取用户所属用户组
  243. $groups = $this->getGroups($uid);
  244. $ids = []; //保存用户所属用户组设置的所有权限规则id
  245. foreach ($groups as $g)
  246. {
  247. $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
  248. }
  249. $ids = array_unique($ids);
  250. return $ids;
  251. }
  252. /**
  253. * 获得用户资料
  254. * @param $uid
  255. * @return mixed
  256. */
  257. protected function getUserInfo($uid)
  258. {
  259. static $user_info = [];
  260. $user = Db::name($this->config['auth_user']);
  261. // 获取用户表主键
  262. $_pk = is_string($user->getPk()) ? $user->getPk() : 'uid';
  263. if (!isset($user_info[$uid]))
  264. {
  265. $user_info[$uid] = $user->where($_pk, $uid)->find();
  266. }
  267. return $user_info[$uid];
  268. }
  269. }