AdminAuth.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. class AdminAuth
  7. {
  8. // 无需验证的路径
  9. protected $except = [
  10. 'admin/login/index',
  11. 'admin/login/send_code',
  12. 'admin/login/out',
  13. 'admin/files_manager/add', // 文件上传
  14. 'admin/contact_way/part_user', // 接待人员
  15. 'admin/product/get_spec_html', // 获取类型下的规格
  16. 'admin/product/get_sku_html', // 获取sku
  17. ];
  18. //默认配置
  19. protected $_config = [
  20. 'auth_on' => true, // 认证开关
  21. 'auth_type' => 1, // 认证方式,1为实时认证;2为登录认证。
  22. 'auth_group' => 'auth_group', // 用户组数据表名
  23. 'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
  24. 'auth_rule' => 'auth_rule' // 权限规则表
  25. ];
  26. /**
  27. * $prefix表前缀
  28. */
  29. public function __construct()
  30. {
  31. // 判断配置
  32. if ( config('AUTH_CONFIG') ) {
  33. //可设置配置项 AUTH_CONFIG, 此配置项为数组。
  34. $this->_config = array_merge($this->_config, config('AUTH_CONFIG'));
  35. }
  36. }
  37. /**
  38. * Handle an incoming request.
  39. *
  40. * @param \Illuminate\Http\Request $request
  41. * @param \Closure $next
  42. * @return mixed
  43. */
  44. public function handle(Request $request, Closure $next)
  45. {
  46. // 当前路径
  47. $path = ltrim($request->getPathInfo(), '/');
  48. // 判断是否需要验证登录
  49. if (!in_array($path, $this->except)) {
  50. // 如果没有登录,重定向到登录页
  51. if ( !admin('uid')) $this->unLogin($request);
  52. // 如果不是超级管理员
  53. if ( !in_array(admin('uid'), explode(',', config('administrator'))) ) {
  54. // 进行验证
  55. if ( !$this->check($path, admin('uid')) ) $this->noAuth('没有权限!');
  56. }
  57. }
  58. // 追加入
  59. $request['authRules'] = $this->getAuthList(admin('uid'),1);
  60. // 返回下一个闭包
  61. return $next($request);
  62. }
  63. /**
  64. * Handle an unauthenticated user.
  65. *
  66. * @param \Illuminate\Http\Request $request
  67. * @return void
  68. *
  69. * @throws AdminAuthException
  70. */
  71. protected function unLogin($request)
  72. {
  73. throw new \App\Exceptions\Admin\AuthException('请先登录',$this->redirectTo($request),0);
  74. }
  75. /**
  76. * Handle an unauthenticated user.
  77. *
  78. * @param \Illuminate\Http\Request $request
  79. * @return void
  80. *
  81. * @throws AdminAuthException
  82. */
  83. protected function noAuth($msg,$url='',$wait=3)
  84. {
  85. throw new \App\Exceptions\Admin\AuthException($msg,$url,$wait);
  86. }
  87. /**
  88. * Get the path the user should be redirected to when they are not authenticated.
  89. *
  90. * @param \Illuminate\Http\Request $request
  91. * @return string|null
  92. */
  93. protected function redirectTo($request)
  94. {
  95. if (!$request->expectsJson()) return route('login');
  96. }
  97. /**
  98. * 检查权限
  99. * @param name string|array 需要验证的规则列表
  100. * @param uid int 认证用户的id
  101. * @return boolean 通过验证返回true;失败返回false
  102. */
  103. public function check($path, $uid, $type = 1)
  104. {
  105. // 未开启验证,直接通过
  106. if ( !$this->_config['auth_on'] ) return true;
  107. // 获取用户需要验证的所有有效规则列表
  108. $authList = $this->getAuthList($uid, $type);
  109. // 切割path
  110. $path = explode('/', $path);
  111. // 没有控制器
  112. if( count($path) < 2 ) $path[] = 'index';
  113. // 没有方法
  114. if( count($path) < 3 ) $path[] = 'index';
  115. // 切割path
  116. $path = implode('/', $path);
  117. // 判断是否通过验证
  118. return in_array($path, $authList);
  119. }
  120. /**
  121. * 根据用户id获取用户组,返回值为数组
  122. * @param int $uid 用户id
  123. * @return array 用户所属的用户组
  124. */
  125. public function getGroups($uid)
  126. {
  127. // 用户组
  128. static $groups = [];
  129. // 存在小组,返回
  130. if ( isset($groups[$uid]) ) return $groups[$uid];
  131. // 从数据库查询
  132. $userrGroups = DB::table($this->_config['auth_group_access'])
  133. ->where([[$this->_config['auth_group_access'].'.user_uid','=',$uid],[$this->_config['auth_group'].'.status','=',1]])
  134. ->join( $this->_config['auth_group'], $this->_config['auth_group_access'].'.group_id','=',$this->_config['auth_group'].'.id')
  135. ->select(['user_uid as uid','group_id','title','rules'])->get()->toArray();
  136. // 获取对应用户的权限组
  137. $groups[$uid] = $userrGroups ?: [];
  138. // 返回用户的权限组
  139. return $groups[$uid];
  140. }
  141. /**
  142. * 获得权限列表
  143. * @param integer $uid 用户id
  144. * @param integer $type
  145. */
  146. protected function getAuthList($uid, $type)
  147. {
  148. // 保存用户验证通过的权限列表
  149. static $_authList = [];
  150. // 验证类型
  151. $key = $uid .'_t_'.implode(',', (array) $type);
  152. // 已经存在权限列表,直接返回
  153. if (isset($_authList[$key])) return $_authList[$key];
  154. // 验证类型,如果不是实时验证
  155. if ( $this->_config['auth_type'] == 2 ) {
  156. // 从session读取验证列表
  157. $session = session('_AUTH_LIST_'.$key);
  158. // 存在则返回
  159. if( !empty($session) ) return $session;
  160. }
  161. // 读取用户所属用户组
  162. $groups = $this->getGroups($uid);
  163. // 保存用户所属用户组设置的所有权限规则id
  164. $ids = [];
  165. // 获取字段值
  166. $ids = array_column($groups,'rules');
  167. // 合并字符值
  168. $ids = array_unique(array_filter(explode(',',implode(',',$ids))));
  169. // 为空
  170. if( empty($ids) ) return [];
  171. // 读取用户组所有权限规则
  172. $rules = Db::table($this->_config['auth_rule'])->whereIn('menu_id',$ids)->pluck('name')->toArray();
  173. // 循环转大写
  174. foreach ( $rules as $rule ) {
  175. // 转小写,截除左边斜杠
  176. $rules[] = ltrim(strtolower($rule),'/');
  177. }
  178. // 去重
  179. $rules = array_unique($rules);
  180. // 如果是登录验证
  181. if ($this->_config['auth_type'] == 2 ) {
  182. // 用户验证列表
  183. $rules[$key] = $rules;
  184. //规则列表结果保存到session
  185. session('_AUTH_LIST_'.$key,$rules);
  186. }
  187. // 返回结果
  188. return $rules;
  189. }
  190. }