You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.2 KiB

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