AccessAuth.php 3.6 KB

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