src/EventSubscriber/ResetPasswordBlockedCreator.php line 52
<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface,
Symfony\Component\HttpKernel\KernelEvents,
Symfony\Component\HttpKernel\Event\ViewEvent,
Symfony\Component\HttpFoundation\RequestStack;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\DTO\ResetPasswordLinkDTO,
App\DTO\ResetPasswordChangeDTO,
App\DTO\CustomerResetPasswordLinkDTO,
App\DTO\CustomerResetPasswordChangeDTO,
App\Repository\ResetPasswordBlockedRepository,
App\Repository\ResetPasswordEntryRepository,
App\StateProcessor\ResetPassword\EntityCreator,
App\Entity\Admin,
App\Entity\Customer;
final class ResetPasswordBlockedCreator implements EventSubscriberInterface
{
const PERIOD = '15 secs';
const MAX = 3;
private RequestStack $requestStack;
private ResetPasswordBlockedRepository $blockedRepository;
private ResetPasswordEntryRepository $entryRepository;
private EntityCreator $entityCreator;
public function __construct(
RequestStack $requestStack,
ResetPasswordBlockedRepository $blockedRepository,
ResetPasswordEntryRepository $entryRepository,
EntityCreator $entityCreator
) {
$this->requestStack = $requestStack;
$this->blockedRepository = $blockedRepository;
$this->entryRepository = $entryRepository;
$this->entityCreator = $entityCreator;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['create', EventPriorities::PRE_VALIDATE]
]
];
}
public function create(ViewEvent $event): void
{
$entity = $event->getControllerResult();
if (! $entity instanceof ResetPasswordLinkDTO
&& ! $entity instanceof ResetPasswordChangeDTO
&& ! $entity instanceof CustomerResetPasswordLinkDTO
&& ! $entity instanceof CustomerResetPasswordChangeDTO
) {
return;
}
$className = $entity instanceof ResetPasswordLinkDTO || $entity instanceof ResetPasswordChangeDTO
? Admin::class
: Customer::class;
$failedAttempts = $this->entryRepository->findAllFailedAttemptsSince(
ip: $this->requestStack->getCurrentRequest()?->getClientIp() ?? 'unkown',
since: new \DateTimeImmutable('- ' . self::PERIOD),
limit: self::MAX,
className: $className
);
if (count($failedAttempts) < self::MAX) {
return;
}
$this->blockedRepository->persist(
$this->entityCreator->block($className),
true
);
return;
}
}