AdminAuth.php 7.6 KB

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