PermissionMiddleware.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * 来自 laravel-admin
  4. */
  5. namespace App\Contracts;
  6. use App\Models\AdminPermission;
  7. use App\Traits\UrlWhitelist;
  8. use App\Utils\Admin;
  9. use App\Utils\PermissionChecker;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Str;
  12. abstract class PermissionMiddleware
  13. {
  14. use UrlWhitelist;
  15. /**
  16. * @var string
  17. */
  18. protected $middlewarePrefix = 'admin.permission:';
  19. /**
  20. * @var array url 白名单
  21. */
  22. protected $urlWhitelist = [];
  23. /**
  24. * Handle an incoming request.
  25. *
  26. * @param \Illuminate\Http\Request $request
  27. * @param \Closure $next
  28. * @param array $args
  29. *
  30. * @return mixed
  31. */
  32. public function handle(Request $request, \Closure $next, ...$args)
  33. {
  34. if (!empty($args) || $this->shouldPassThrough($request)) {
  35. return $next($request);
  36. }
  37. if (!Admin::user()) {
  38. PermissionChecker::error();
  39. }
  40. if ($this->checkRoutePermission($request)) {
  41. return $next($request);
  42. }
  43. if (!Admin::user()->allPermissions()->first(function (AdminPermission $permission) use ($request) {
  44. return PermissionChecker::shouldPassThrough($permission, $request);
  45. })) {
  46. PermissionChecker::error();
  47. }
  48. return $next($request);
  49. }
  50. /**
  51. * 如果路由的中间件组中, 有以 'admin.permission:' 开头的, 说明是单独设置了权限, 要优先处理
  52. *
  53. * @param Request $request
  54. *
  55. * @return bool
  56. */
  57. public function checkRoutePermission(Request $request)
  58. {
  59. if (!$middleware = collect($request->route()->middleware())->first(function ($middleware) {
  60. return Str::startsWith($middleware, $this->middlewarePrefix);
  61. })) {
  62. return false;
  63. }
  64. $args = explode(',', str_replace($this->middlewarePrefix, '', $middleware));
  65. $method = array_shift($args);
  66. if (!method_exists(PermissionChecker::class, $method)) {
  67. throw new \InvalidArgumentException("无效的权限检测方法 [ $method ]");
  68. }
  69. call_user_func_array([PermissionChecker::class, $method], [$args]);
  70. return true;
  71. }
  72. protected function urlWhitelist(): array
  73. {
  74. return array_map(function ($url) {
  75. return Admin::url($url);
  76. }, $this->urlWhitelist);
  77. }
  78. }