AccessAuth.php 3.4 KB

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