Auth.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <?php
  2. /**
  3. * 洛阳赤炎鹰网络科技有限公司
  4. * https://www.cyyvip.com
  5. * Copyright (c) 2022 赤店商城 All rights reserved.
  6. */
  7. // +----------------------------------------------------------------------
  8. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  9. // +----------------------------------------------------------------------
  10. // | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
  11. // +----------------------------------------------------------------------
  12. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  13. // +----------------------------------------------------------------------
  14. // | Author: luofei614 <weibo.com/luofei614> 
  15. // +----------------------------------------------------------------------
  16. namespace Think;
  17. /**
  18. * 权限认证类
  19. * 功能特性:
  20. * 1,是对规则进行认证,不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
  21. * $auth=new Auth(); $auth->check('规则名称','用户id')
  22. * 2,可以同时对多条规则进行认证,并设置多条规则的关系(or或者and)
  23. * $auth=new Auth(); $auth->check('规则1,规则2','用户id','and')
  24. * 第三个参数为and时表示,用户需要同时具有规则1和规则2的权限。 当第三个参数为or时,表示用户值需要具备其中一个条件即可。默认为or
  25. * 3,一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
  26. *
  27. * 4,支持规则表达式。
  28. * 在think_auth_rule 表中定义一条规则时,如果type为1, condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100 表示用户的分数在5-100之间时这条规则才会通过。
  29. */
  30. //数据库
  31. /*
  32. -- ----------------------------
  33. -- think_auth_rule,规则表,
  34. -- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证
  35. -- ----------------------------
  36. DROP TABLE IF EXISTS `think_auth_rule`;
  37. CREATE TABLE `think_auth_rule` (
  38. `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  39. `name` char(80) NOT NULL DEFAULT '',
  40. `title` char(20) NOT NULL DEFAULT '',
  41. `type` tinyint(1) NOT NULL DEFAULT '1',
  42. `status` tinyint(1) NOT NULL DEFAULT '1',
  43. `condition` char(100) NOT NULL DEFAULT '', # 规则附件条件,满足附加条件的规则,才认为是有效的规则
  44. PRIMARY KEY (`id`),
  45. UNIQUE KEY `name` (`name`)
  46. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  47. -- ----------------------------
  48. -- think_auth_group 用户组表,
  49. -- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用
  50. -- ----------------------------
  51. DROP TABLE IF EXISTS `think_auth_group`;
  52. CREATE TABLE `think_auth_group` (
  53. `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  54. `title` char(100) NOT NULL DEFAULT '',
  55. `status` tinyint(1) NOT NULL DEFAULT '1',
  56. `rules` char(80) NOT NULL DEFAULT '',
  57. PRIMARY KEY (`id`)
  58. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  59. -- ----------------------------
  60. -- think_auth_group_access 用户组明细表
  61. -- uid:用户id,group_id:用户组id
  62. -- ----------------------------
  63. DROP TABLE IF EXISTS `think_auth_group_access`;
  64. CREATE TABLE `think_auth_group_access` (
  65. `uid` mediumint(8) unsigned NOT NULL,
  66. `group_id` mediumint(8) unsigned NOT NULL,
  67. UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
  68. KEY `uid` (`uid`),
  69. KEY `group_id` (`group_id`)
  70. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  71. */
  72. class Auth{
  73. //默认配置
  74. protected $_config = array(
  75. 'AUTH_ON' => true, // 认证开关
  76. 'AUTH_TYPE' => 1, // 认证方式,1为实时认证;2为登录认证。
  77. 'AUTH_GROUP' => 'auth_group', // 用户组数据表名
  78. 'AUTH_GROUP_ACCESS' => 'auth_group_access', // 用户-用户组关系表
  79. 'AUTH_RULE' => 'auth_rule', // 权限规则表
  80. 'AUTH_USER' => 'member' // 用户信息表
  81. );
  82. public function __construct() {
  83. $prefix = C('DB_PREFIX');
  84. $this->_config['AUTH_GROUP'] = $prefix.$this->_config['AUTH_GROUP'];
  85. $this->_config['AUTH_RULE'] = $prefix.$this->_config['AUTH_RULE'];
  86. $this->_config['AUTH_USER'] = $prefix.$this->_config['AUTH_USER'];
  87. $this->_config['AUTH_GROUP_ACCESS'] = $prefix.$this->_config['AUTH_GROUP_ACCESS'];
  88. if (C('AUTH_CONFIG')) {
  89. //可设置配置项 AUTH_CONFIG, 此配置项为数组。
  90. $this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
  91. }
  92. }
  93. /**
  94. * 检查权限
  95. * @param name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
  96. * @param uid int 认证用户的id
  97. * @param string mode 执行check的模式
  98. * @param relation string 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
  99. * @return boolean 通过验证返回true;失败返回false
  100. */
  101. public function check($name, $uid, $type=1, $mode='url', $relation='or') {
  102. if (!$this->_config['AUTH_ON'])
  103. return true;
  104. $authList = $this->getAuthList($uid,$type); //获取用户需要验证的所有有效规则列表
  105. if (is_string($name)) {
  106. $name = strtolower($name);
  107. if (strpos($name, ',') !== false) {
  108. $name = explode(',', $name);
  109. } else {
  110. $name = array($name);
  111. }
  112. }
  113. $list = array(); //保存验证通过的规则名
  114. if ($mode=='url') {
  115. $REQUEST = unserialize( strtolower(serialize($_REQUEST)) );
  116. }
  117. foreach ( $authList as $auth ) {
  118. $query = preg_replace('/^.+\?/U','',$auth);
  119. if ($mode=='url' && $query!=$auth ) {
  120. parse_str($query,$param); //解析规则中的param
  121. $intersect = array_intersect_assoc($REQUEST,$param);
  122. $auth = preg_replace('/\?.*$/U','',$auth);
  123. if ( in_array($auth,$name) && $intersect==$param ) { //如果节点相符且url参数满足
  124. $list[] = $auth ;
  125. }
  126. }else if (in_array($auth , $name)){
  127. $list[] = $auth ;
  128. }
  129. }
  130. if ($relation == 'or' and !empty($list)) {
  131. return true;
  132. }
  133. $diff = array_diff($name, $list);
  134. if ($relation == 'and' and empty($diff)) {
  135. return true;
  136. }
  137. return false;
  138. }
  139. /**
  140. * 根据用户id获取用户组,返回值为数组
  141. * @param uid int 用户id
  142. * @return array 用户所属的用户组 array(
  143. * array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
  144. * ...)
  145. */
  146. public function getGroups($uid) {
  147. static $groups = array();
  148. if (isset($groups[$uid]))
  149. return $groups[$uid];
  150. $user_groups = M()
  151. ->table($this->_config['AUTH_GROUP_ACCESS'] . ' a')
  152. ->where("a.uid='$uid' and g.status='1'")
  153. ->join($this->_config['AUTH_GROUP']." g on a.group_id=g.id")
  154. ->field('uid,group_id,title,rules')->select();
  155. $groups[$uid]=$user_groups?:array();
  156. return $groups[$uid];
  157. }
  158. /**
  159. * 获得权限列表
  160. * @param integer $uid 用户id
  161. * @param integer $type
  162. */
  163. protected function getAuthList($uid,$type) {
  164. static $_authList = array(); //保存用户验证通过的权限列表
  165. $t = implode(',',(array)$type);
  166. if (isset($_authList[$uid.$t])) {
  167. return $_authList[$uid.$t];
  168. }
  169. if( $this->_config['AUTH_TYPE']==2 && isset($_SESSION['_AUTH_LIST_'.$uid.$t])){
  170. return $_SESSION['_AUTH_LIST_'.$uid.$t];
  171. }
  172. //读取用户所属用户组
  173. $groups = $this->getGroups($uid);
  174. $ids = array();//保存用户所属用户组设置的所有权限规则id
  175. foreach ($groups as $g) {
  176. $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
  177. }
  178. $ids = array_unique($ids);
  179. if (empty($ids)) {
  180. $_authList[$uid.$t] = array();
  181. return array();
  182. }
  183. $map=array(
  184. 'id'=>array('in',$ids),
  185. 'type'=>$type,
  186. 'status'=>1,
  187. );
  188. //读取用户组所有权限规则
  189. $rules = M()->table($this->_config['AUTH_RULE'])->where($map)->field('condition,name')->select();
  190. //循环规则,判断结果。
  191. $authList = array(); //
  192. foreach ($rules as $rule) {
  193. if (!empty($rule['condition'])) { //根据condition进行验证
  194. $user = $this->getUserInfo($uid);//获取用户信息,一维数组
  195. $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
  196. //dump($command);//debug
  197. @(eval('$condition=(' . $command . ');'));
  198. if ($condition) {
  199. $authList[] = strtolower($rule['name']);
  200. }
  201. } else {
  202. //只要存在就记录
  203. $authList[] = strtolower($rule['name']);
  204. }
  205. }
  206. $_authList[$uid.$t] = $authList;
  207. if($this->_config['AUTH_TYPE']==2){
  208. //规则列表结果保存到session
  209. $_SESSION['_AUTH_LIST_'.$uid.$t]=$authList;
  210. }
  211. return array_unique($authList);
  212. }
  213. /**
  214. * 获得用户资料,根据自己的情况读取数据库
  215. */
  216. protected function getUserInfo($uid) {
  217. static $userinfo=array();
  218. if(!isset($userinfo[$uid])){
  219. $userinfo[$uid]=M()->where(array('uid'=>$uid))->table($this->_config['AUTH_USER'])->find();
  220. }
  221. return $userinfo[$uid];
  222. }
  223. }