How to create IP blacklist in Symfony2?

前端 未结 6 1241
刺人心
刺人心 2021-02-08 17:53

Yes, I know there\'s Voter tutorial in cookbook. But I\'m looking for something slightly different. I need two different layers of blacklisting:

  1. deny certain IP to
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-08 18:09

    To the first problem – there are filters in EventDispatcher, so you can throw AccessDeniedHttpException before Controller start process request.

    To the second problem – if you use custom User Provider you can check for banned IP addresses in UserRepository.

    namespace Acme\SecurityBundle\Entity;
    //… some namespaces
    use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
    
    /**
     * UserRepository
     */
    class UserRepository extends … implements …
    {
    
        public function loadUserByUsername($username)
        {
            if ( $this->isBanned() ) {
                throw new AccessDeniedHttpException("You're banned!");
            }
            //… load user from DB
        }
    
        //… some other methods
    
        private function isBanned()
        {
            $q = $this->getEntityManager()->createQuery('SELECT b FROM AcmeSecurityBundle:BlackList b WHERE b.ip = :ip')
                ->setParameter('ip', @$_SERVER['REMOTE_ADDR'])
                ->setMaxResults(1)
            ;
            $blackList = $q->getOneOrNullResult();
    
            //… check if is banned
        }
    
    }
    

提交回复
热议问题