AuthRequest.php 2.5 KB

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