LoginForm.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Livewire\Forms;
  3. use Illuminate\Auth\Events\Lockout;
  4. use Illuminate\Support\Facades\Auth;
  5. use Illuminate\Support\Facades\RateLimiter;
  6. use Illuminate\Support\Str;
  7. use Illuminate\Validation\ValidationException;
  8. use Livewire\Attributes\Validate;
  9. use Livewire\Form;
  10. class LoginForm extends Form
  11. {
  12. #[Validate('required|string|email')]
  13. public string $email = '';
  14. #[Validate('required|string')]
  15. public string $password = '';
  16. #[Validate('boolean')]
  17. public bool $remember = false;
  18. /**
  19. * Attempt to authenticate the request's credentials.
  20. *
  21. * @throws \Illuminate\Validation\ValidationException
  22. */
  23. public function authenticate(): void
  24. {
  25. $this->ensureIsNotRateLimited();
  26. if (! Auth::attempt($this->only(['email', 'password']), $this->remember)) {
  27. RateLimiter::hit($this->throttleKey());
  28. throw ValidationException::withMessages([
  29. 'form.email' => trans('auth.failed'),
  30. ]);
  31. }
  32. RateLimiter::clear($this->throttleKey());
  33. }
  34. /**
  35. * Ensure the authentication request is not rate limited.
  36. */
  37. protected function ensureIsNotRateLimited(): void
  38. {
  39. if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
  40. return;
  41. }
  42. event(new Lockout(request()));
  43. $seconds = RateLimiter::availableIn($this->throttleKey());
  44. throw ValidationException::withMessages([
  45. 'form.email' => trans('auth.throttle', [
  46. 'seconds' => $seconds,
  47. 'minutes' => ceil($seconds / 60),
  48. ]),
  49. ]);
  50. }
  51. /**
  52. * Get the authentication rate limiting throttle key.
  53. */
  54. protected function throttleKey(): string
  55. {
  56. return Str::transliterate(Str::lower($this->email).'|'.request()->ip());
  57. }
  58. }