<?php
namespace Nen\Bundle\KennisbankPlatformBundle\Security;
use Doctrine\ORM\EntityManagerInterface;
use Nen\Bundle\KennisbankPlatformBundle\Entity\Ip;
use App\Entity\User;
use Nen\Bundle\KennisbankPlatformBundle\Support\IpPacker;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class IpLoginAuthenticator extends AbstractAuthenticator
{
private Security $security;
private EntityManagerInterface $em;
public function __construct(Security $security, EntityManagerInterface $em)
{
$this->security = $security;
$this->em = $em;
}
public function loadUserByIp($ip): ?User
{
$packedIp = IpPacker::pack($ip);
$qb = $this->em->createQueryBuilder();
$result = $qb
->select('i', 'u', 'c')
->from(Ip::class, 'i')
->innerJoin('i.user', 'u')
->innerJoin('u.company', 'c')
->where(
$qb->expr()->lte('i.from', $packedIp),
$qb->expr()->gte('i.to', $packedIp)
)
->setMaxResults(1)
->getQuery()
->execute();
if (empty($result)) {
return null;
}
/** @var Ip $ip */
$ip = $result[0];
if (!$ip->getUser()->hasValidLicense()) {
return null;
}
return $ip->getUser();
}
public function supports(Request $request): bool
{
return $this->security->getUser() === null;
}
public function authenticate(Request $request): PassportInterface
{
$ip = $request->getClientIp();
return new SelfValidatingPassport(
new UserBadge($ip, [$this, 'loadUserByIp'])
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return null;
}
}