StoreLoginRequest.php 2.2KB

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