LoginRequest.php 2.2 KB

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