src/Security/IpVoter.php line 14

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by Elements.at New Media Solutions GmbH
  4.  *
  5.  */
  6. namespace App\Security;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. class IpVoter extends Voter
  11. {
  12.     /** @var string[] */
  13.     private array $allowedIps = [
  14.         '89.26.34.65',
  15.         '89.26.34.74',
  16.         '3.66.47.185',
  17.         '3.123.204.232',
  18.     ];
  19.     /** @var string[] */
  20.     private array $allowedSubnets = [
  21.         '10.85',
  22.         '192.168',
  23.     ];
  24.     /**
  25.      * @param string $attribute
  26.      * @param mixed $subject
  27.      *
  28.      * @return bool
  29.      */
  30.     protected function supports(string $attribute$subject): bool
  31.     {
  32.         if ($subject instanceof Request) {
  33.             return strpos($subject->getPathInfo(), 'booking-api');
  34.         }
  35.         return false;
  36.     }
  37.     /**
  38.      * @param string $attribute
  39.      * @param mixed $subject
  40.      * @param TokenInterface $token
  41.      *
  42.      * @return bool
  43.      *
  44.      * @throws \Exception
  45.      */
  46.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  47.     {
  48.         /** @var Request $clientIp */
  49.         $clientIp $subject->getClientIp();
  50.         $inAllowedSubNet false;
  51.         foreach ($this->allowedSubnets as $allowedSubnet) {
  52.             if (preg_match("/^$allowedSubnet/"$clientIp)) {
  53.                 $inAllowedSubNet true;
  54.                 break;
  55.             }
  56.         }
  57.         $inAllowedIps in_array($clientIp$this->allowedIps);
  58.         if (!$inAllowedSubNet && !$inAllowedIps) {
  59.             //todo consider removing exception as it is only useful for debugging. Returning false here has the same effect.
  60.             throw new \Exception('Your IP did not match our whitelist. The IP we see is : '.$subject->getClientIp());
  61.         }
  62.         return true;
  63.     }
  64. }