Authorize.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Illuminate\Auth\Middleware;
  3. use Closure;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Contracts\Auth\Access\Gate;
  6. use Illuminate\Contracts\Auth\Factory as Auth;
  7. class Authorize
  8. {
  9. /**
  10. * The authentication factory instance.
  11. *
  12. * @var \Illuminate\Contracts\Auth\Factory
  13. */
  14. protected $auth;
  15. /**
  16. * The gate instance.
  17. *
  18. * @var \Illuminate\Contracts\Auth\Access\Gate
  19. */
  20. protected $gate;
  21. /**
  22. * Create a new middleware instance.
  23. *
  24. * @param \Illuminate\Contracts\Auth\Factory $auth
  25. * @param \Illuminate\Contracts\Auth\Access\Gate $gate
  26. * @return void
  27. */
  28. public function __construct(Auth $auth, Gate $gate)
  29. {
  30. $this->auth = $auth;
  31. $this->gate = $gate;
  32. }
  33. /**
  34. * Handle an incoming request.
  35. *
  36. * @param \Illuminate\Http\Request $request
  37. * @param \Closure $next
  38. * @param string $ability
  39. * @param array|null ...$models
  40. * @return mixed
  41. *
  42. * @throws \Illuminate\Auth\AuthenticationException
  43. * @throws \Illuminate\Auth\Access\AuthorizationException
  44. */
  45. public function handle($request, Closure $next, $ability, ...$models)
  46. {
  47. $this->auth->authenticate();
  48. $this->gate->authorize($ability, $this->getGateArguments($request, $models));
  49. return $next($request);
  50. }
  51. /**
  52. * Get the arguments parameter for the gate.
  53. *
  54. * @param \Illuminate\Http\Request $request
  55. * @param array|null $models
  56. * @return array|string|\Illuminate\Database\Eloquent\Model
  57. */
  58. protected function getGateArguments($request, $models)
  59. {
  60. if (is_null($models)) {
  61. return [];
  62. }
  63. return collect($models)->map(function ($model) use ($request) {
  64. return $model instanceof Model ? $model : $this->getModel($request, $model);
  65. })->all();
  66. }
  67. /**
  68. * Get the model to authorize.
  69. *
  70. * @param \Illuminate\Http\Request $request
  71. * @param string $model
  72. * @return \Illuminate\Database\Eloquent\Model|string
  73. */
  74. protected function getModel($request, $model)
  75. {
  76. return $this->isClassName($model) ? $model : $request->route($model);
  77. }
  78. /**
  79. * Checks if the given string looks like a fully qualified class name.
  80. *
  81. * @param string $value
  82. * @return bool
  83. */
  84. protected function isClassName($value)
  85. {
  86. return strpos($value, '\\') !== false;
  87. }
  88. }