AccessAuth.php 3.1 KB

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