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