src/Security/Voter/AuthAttemptVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\AuthAttempt;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. class AuthAttemptVoter extends Voter
  10. {
  11.     protected RequestStack $requestStack;
  12.     protected EntityManagerInterface $entityManager;
  13.     private ContainerInterface $container;
  14.     public function __construct(
  15.         RequestStack $requestStack,
  16.         EntityManagerInterface $entityManager,
  17.         ContainerInterface $container
  18.     ) {
  19.         $this->requestStack $requestStack;
  20.         $this->entityManager $entityManager;
  21.         $this->container $container;
  22.     }
  23.     const VIEW_AUTH_FORM_CAPTCHA 'view_auth_form_captcha';
  24.     protected function supports($attribute$subject)
  25.     {
  26.         return in_array($attribute, [self::VIEW_AUTH_FORM_CAPTCHA]);
  27.     }
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  29.     {
  30.         // ... (check conditions and return true to grant permission) ...
  31.         switch ($attribute) {
  32.             case self::VIEW_AUTH_FORM_CAPTCHA:
  33.                 return $this->isCanViewAuthFormCaptcha();
  34.                 break;
  35.         }
  36.         return false;
  37.     }
  38.     public function isCanViewAuthFormCaptcha()
  39.     {
  40.         if (false === $this->container->getParameter('ewz_recaptcha.enabled')) {
  41.             return false;
  42.         }
  43.         $authAttemptsRepo $this->entityManager->getRepository(AuthAttempt::class);
  44.         $request $this->requestStack->getCurrentRequest();
  45.         $clientIp $request->headers->get('X-Real-IP'$request->getClientIp());
  46.         $count $authAttemptsRepo->getTodayCount($clientIp$request->attributes->get('_route'));
  47.         return $count 3;
  48.     }
  49. }