123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- /**
- * @Name
- * @Description
- * @Author 刘学玺
- * @Date 2024/8/23 12:24
- */
- namespace App\Http\Requests\Backend\Server\System;
- use App\Http\Requests\Request;
- use Illuminate\Auth\Events\Lockout;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\RateLimiter;
- use Illuminate\Support\Facades\Route;
- use Illuminate\Support\Str;
- use Illuminate\Validation\ValidationException;
- class AuthRequest extends Request
- {
- /**
- * Determine if the user is authorized to make this request.
- */
- public function authorize(): bool
- {
- return true;
- }
- /**
- * Get the validation rules that apply to the request.
- *
- * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
- */
- public function rules(): array
- {
- $rules = [];
- $actionName = last(explode('@', Route::current()->getActionName()));
- if ($actionName === 'login') {
- $rules['username'] = ['required', 'string'];
- $rules['password'] = ['required', 'string'];
- }
- return $rules;
- }
- /**
- * Attempt to authenticate the request's credentials.
- *
- * @throws \Illuminate\Validation\ValidationException
- */
- public function authenticate(): void
- {
- $this->ensureIsNotRateLimited();
- $credentials = ['name' => $this->get('username'), 'password' => $this->get('password')];
- if (!Auth::attempt($credentials, $this->boolean('remember'))) {
- RateLimiter::hit($this->throttleKey());
- // 账号密码错误
- throw ValidationException::withMessages([
- 'username' => __('auth.failed'),
- ]);
- }
- RateLimiter::clear($this->throttleKey());
- }
- /**
- * Ensure the login request is not rate limited.
- *
- * @throws \Illuminate\Validation\ValidationException
- */
- public function ensureIsNotRateLimited(): void
- {
- if (!RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
- return;
- }
- event(new Lockout($this));
- $seconds = RateLimiter::availableIn($this->throttleKey());
- throw ValidationException::withMessages([
- 'username' => trans('auth.throttle', [
- 'seconds' => $seconds,
- 'minutes' => ceil($seconds / 60),
- ]),
- ]);
- }
- /**
- * Get the rate limiting throttle key for the request.
- */
- public function throttleKey(): string
- {
- return Str::transliterate(Str::lower($this->input('username')) . '|' . $this->ip());
- }
- }
|