AccessAuth.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Http\Middleware\Manager;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use App\Models\Manager\AuthRule;
  6. // 访问权限验证
  7. class AccessAuth
  8. {
  9. // 无需验证的路径
  10. protected $except = [
  11. 'manager/login/index',
  12. ];
  13. //默认配置
  14. protected $_config = [
  15. 'auth_on' => true, // 认证开关
  16. 'auth_type' => 1, // 认证方式,1为实时认证;2为登录认证。
  17. 'auth_group' => 'auth_group', // 用户组数据表名
  18. 'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
  19. 'auth_rule' => 'auth_rule' // 权限规则表
  20. ];
  21. /**
  22. * $prefix表前缀
  23. */
  24. public function __construct()
  25. {
  26. // 判断配置
  27. if (config('AUTH_CONFIG')) {
  28. //可设置配置项 AUTH_CONFIG, 此配置项为数组。
  29. $this->_config = array_merge($this->_config, config('AUTH_CONFIG'));
  30. }
  31. }
  32. /**
  33. * Handle an incoming request.
  34. *
  35. * @param \Illuminate\Http\Request $request
  36. * @param \Closure $next
  37. * @return mixed
  38. */
  39. public function handle(Request $request, Closure $next)
  40. {
  41. // 当前路径
  42. $path = ltrim($request->getPathInfo(), '/');
  43. // 判断是否需要验证登录
  44. if (!in_array($path, $this->except)) {
  45. // 用户ID
  46. $uid = request('access_token.uid', 0);
  47. // 如果未登录
  48. if (!$uid) return json_send(['code' => 'no_login', 'msg' => '请登录账号', 'data' => ['请您登录']]);
  49. // 如果不是超级管理员
  50. if (!request('access_token.is_super', 0)) {
  51. // 进行验证
  52. if (!$this->check($path, $uid)) return json_send(['code' => 'error', 'msg' => '您没有操作权限', 'data' => ['没有操作权限']]);
  53. }
  54. }
  55. // 返回下一个闭包
  56. return $next($request);
  57. }
  58. /**
  59. * 检查权限
  60. * @param name string|array 需要验证的规则列表
  61. * @param uid int 认证用户的id
  62. * @return boolean 通过验证返回true;失败返回false
  63. */
  64. private function check($path, $uid)
  65. {
  66. // 未开启验证,直接通过
  67. if (!$this->_config['auth_on']) return true;
  68. // 获取用户需要验证的所有有效规则列表
  69. $authList = (new AuthRule())->getAuthList($uid, 'manager');
  70. // 切割path
  71. $path = explode('/', $path);
  72. // 没有控制器
  73. if (count($path) < 2) $path[] = 'index';
  74. // 没有方法
  75. if (count($path) < 3) $path[] = 'index';
  76. // 切割path
  77. $path = implode('/', $path);
  78. // 判断是否通过验证
  79. return in_array($path, $authList);
  80. }
  81. }