LoginRequest.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Http\Requests\Auth;
  3. use Illuminate\Auth\Events\Lockout;
  4. use Illuminate\Foundation\Http\FormRequest;
  5. use Illuminate\Support\Facades\Auth;
  6. use Illuminate\Support\Facades\RateLimiter;
  7. use Illuminate\Support\Str;
  8. use Illuminate\Validation\ValidationException;
  9. class LoginRequest extends FormRequest
  10. {
  11. /**
  12. * Determine if the user is authorized to make this request.
  13. *
  14. * @return bool
  15. */
  16. public function authorize()
  17. {
  18. return true;
  19. }
  20. /**
  21. * Get the validation rules that apply to the request.
  22. *
  23. * @return array
  24. */
  25. public function rules()
  26. {
  27. return [
  28. 'email' => ['required', 'string', 'email'],
  29. 'password' => ['required', 'string'],
  30. ];
  31. }
  32. /**
  33. * Attempt to authenticate the request's credentials.
  34. *
  35. * @return void
  36. *
  37. * @throws \Illuminate\Validation\ValidationException
  38. */
  39. public function authenticate()
  40. {
  41. $this->ensureIsNotRateLimited();
  42. if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
  43. RateLimiter::hit($this->throttleKey());
  44. throw ValidationException::withMessages([
  45. 'email' => trans('auth.failed'),
  46. ]);
  47. }
  48. RateLimiter::clear($this->throttleKey());
  49. }
  50. /**
  51. * Ensure the login request is not rate limited.
  52. *
  53. * @return void
  54. *
  55. * @throws \Illuminate\Validation\ValidationException
  56. */
  57. public function ensureIsNotRateLimited()
  58. {
  59. if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
  60. return;
  61. }
  62. event(new Lockout($this));
  63. $seconds = RateLimiter::availableIn($this->throttleKey());
  64. throw ValidationException::withMessages([
  65. 'email' => trans('auth.throttle', [
  66. 'seconds' => $seconds,
  67. 'minutes' => ceil($seconds / 60),
  68. ]),
  69. ]);
  70. }
  71. /**
  72. * Get the rate limiting throttle key for the request.
  73. *
  74. * @return string
  75. */
  76. public function throttleKey()
  77. {
  78. return Str::lower($this->input('email')).'|'.$this->ip();
  79. }
  80. }