Files
star-cloud/app/Http/Requests/Auth/LoginRequest.php

97 lines
2.4 KiB
PHP
Raw Normal View History

2025-11-21 17:15:27 +08:00
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* 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
{
return [
2026-01-12 11:23:41 +08:00
'username' => ['required', 'string'],
2025-11-21 17:15:27 +08:00
'password' => ['required', 'string'],
];
}
2026-01-12 11:23:41 +08:00
/**
* 取得驗證規則的自訂錯誤訊息
*/
public function messages(): array
{
return [
'username.required' => '請輸入帳號',
'password.required' => '請輸入密碼',
];
}
2025-11-21 17:15:27 +08:00
/**
* Attempt to authenticate the request's credentials.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
2026-01-12 11:23:41 +08:00
if (! Auth::attempt($this->only('username', 'password'), $this->boolean('remember'))) {
2025-11-21 17:15:27 +08:00
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
2026-01-12 11:23:41 +08:00
'username' => trans('auth.failed'),
2025-11-21 17:15:27 +08:00
]);
}
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([
2026-01-12 11:23:41 +08:00
'username' => trans('auth.throttle', [
2025-11-21 17:15:27 +08:00
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
2026-01-12 11:23:41 +08:00
return Str::transliterate(Str::lower($this->string('username')).'|'.$this->ip());
2025-11-21 17:15:27 +08:00
}
}