111 lines
2.9 KiB
PHP
111 lines
2.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Requests\Auth;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Auth\Events\Lockout;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\RateLimiter;
|
|
use Illuminate\Validation\Rules\Password;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Uwil\LaravelBackend\Requests\Auth\LoginRequest as BackendLoginRequest;
|
|
|
|
/**
|
|
* Handles backend login form validation, authentication and rate limiting.
|
|
*/
|
|
class LoginRequest extends BackendLoginRequest
|
|
{
|
|
/**
|
|
* Get the validation rules that apply to the request.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
#[\Override]
|
|
public function rules(): array
|
|
{
|
|
return [
|
|
'email' => 'required|string|email:rfc,strict,dns,spoof,filter',
|
|
'password' => [
|
|
'required',
|
|
'max:255',
|
|
Password::min(8)
|
|
->letters()
|
|
->mixedCase()
|
|
->numbers()
|
|
->symbols()
|
|
->uncompromised(),
|
|
],
|
|
'remember' => 'boolean',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get custom attributes for validator errors.
|
|
*
|
|
* @return array<string, string>
|
|
*/
|
|
#[\Override]
|
|
public function attributes(): array
|
|
{
|
|
return [
|
|
'email' => trans('validation.attributes.email'),
|
|
'password' => trans('validation.attributes.password'),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Attempt to authenticate the request's credentials.
|
|
*
|
|
* @throws \Illuminate\Validation\ValidationException Wrong email.
|
|
*/
|
|
#[\Override]
|
|
public function authenticate(): void
|
|
{
|
|
$this->ensureIsNotRateLimited();
|
|
|
|
$user = User::query()
|
|
->where('email', $this->input('email'))
|
|
->first();
|
|
|
|
if (
|
|
! $user
|
|
|| ! $user->userPassword
|
|
|| ! Hash::check($this->input('password'), $user->userPassword->password)
|
|
) {
|
|
RateLimiter::hit($this->throttleKey());
|
|
throw ValidationException::withMessages([
|
|
'email' => trans('auth.failed'),
|
|
]);
|
|
}
|
|
|
|
Auth::guard('backend')->login($user, $this->boolean('remember'));
|
|
RateLimiter::clear($this->throttleKey());
|
|
}
|
|
|
|
/**
|
|
* Ensure the login request is not rate limited.
|
|
*
|
|
* @throws \Illuminate\Validation\ValidationException Wrong email.
|
|
*/
|
|
#[\Override]
|
|
public function ensureIsNotRateLimited(): void
|
|
{
|
|
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
|
|
return;
|
|
}
|
|
|
|
event(new Lockout($this));
|
|
|
|
$seconds = RateLimiter::availableIn($this->throttleKey());
|
|
|
|
throw ValidationException::withMessages([
|
|
'email' => trans('auth.throttle', [
|
|
'seconds' => $seconds,
|
|
'minutes' => ceil($seconds / 60),
|
|
]),
|
|
]);
|
|
}
|
|
}
|