LoginRequest.php 2.3 KB

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