AccessAuth.php 3.1 KB

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