AdminAuth.php 8.1 KB

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