LimitRequestMiddleware.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Cache\RateLimiter;
  5. use Illuminate\Cache\RateLimiting\Unlimited;
  6. use Illuminate\Http\Exceptions\HttpResponseException;
  7. use Illuminate\Http\Exceptions\ThrottleRequestsException;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Routing\Middleware\ThrottleRequests;
  10. use Illuminate\Support\Arr;
  11. use Illuminate\Support\InteractsWithTime;
  12. use Illuminate\Support\Str;
  13. use Symfony\Component\HttpFoundation\Response;
  14. class LimitRequestMiddleware extends ThrottleRequests
  15. {
  16. /**
  17. * The rate limiter instance.
  18. *
  19. * @var \Illuminate\Cache\RateLimiter
  20. */
  21. protected $limiter;
  22. /**
  23. * Create a new request throttler.
  24. *
  25. * @param \Illuminate\Cache\RateLimiter $limiter
  26. * @return void
  27. */
  28. public function __construct(RateLimiter $limiter)
  29. {
  30. $this->limiter = $limiter;
  31. }
  32. /**
  33. * Handle an incoming request.
  34. *
  35. * @param \Illuminate\Http\Request $request
  36. * @param \Closure $next
  37. * @param int|string $maxAttempts
  38. * @param float|int $decayMinutes
  39. * @param string $prefix
  40. * @return \Symfony\Component\HttpFoundation\Response
  41. *
  42. * @throws \Illuminate\Http\Exceptions\ThrottleRequestsException
  43. */
  44. public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
  45. {
  46. try {
  47. if (is_string($maxAttempts)
  48. && func_num_args() === 3
  49. && ! is_null($limiter = $this->limiter->limiter($maxAttempts))) {
  50. return $this->handleRequestUsingNamedLimiter($request, $next, $maxAttempts, $limiter);
  51. }
  52. return $this->handleRequest(
  53. $request,
  54. $next,
  55. [
  56. (object) [
  57. 'key' => $prefix.$this->resolveRequestSignature($request),
  58. 'maxAttempts' => $this->resolveMaxAttempts($request, $maxAttempts),
  59. 'decayMinutes' => $decayMinutes,
  60. 'responseCallback' => null,
  61. ],
  62. ]
  63. );
  64. }catch (\Exception $exception){
  65. return response()->json([
  66. 'code'=>50000,
  67. 'status' => 'fail',
  68. 'message' => '验证码已发送,请在一分钟后请求',
  69. 'data' =>null,
  70. 'error' => null,
  71. ]);
  72. }
  73. }
  74. }