<?php
/**
* Created by Elements.at New Media Solutions GmbH
*
*/
namespace App\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class IpVoter extends Voter
{
/** @var string[] */
private array $allowedIps = [
'89.26.34.65',
'89.26.34.74',
'3.66.47.185',
'3.123.204.232',
];
/** @var string[] */
private array $allowedSubnets = [
'10.85',
'192.168',
];
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
if ($subject instanceof Request) {
return strpos($subject->getPathInfo(), 'booking-api');
}
return false;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*
* @throws \Exception
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var Request $clientIp */
$clientIp = $subject->getClientIp();
$inAllowedSubNet = false;
foreach ($this->allowedSubnets as $allowedSubnet) {
if (preg_match("/^$allowedSubnet/", $clientIp)) {
$inAllowedSubNet = true;
break;
}
}
$inAllowedIps = in_array($clientIp, $this->allowedIps);
if (!$inAllowedSubNet && !$inAllowedIps) {
//todo consider removing exception as it is only useful for debugging. Returning false here has the same effect.
throw new \Exception('Your IP did not match our whitelist. The IP we see is : '.$subject->getClientIp());
}
return true;
}
}