0

I come to you today because I'm facing a problem with my Symfony's project. I'd like to restrict a service to a specific host. The project includes several interfaces for different kind of users. The thing is I need to declare some services only for a specific host in order to not interfer with the other interfaces.

I've tried to add the host clause in the service definition but Symfony doesn't take it.. The temporary solution is to check the host inside the service but it's not clean..

Thanks to everyone who helps !

Ciao !

Thomas CEDRINI
  • 171
  • 1
  • 3
  • 10

1 Answers1

0

I'd stick with the check inside the service; of course you should use a configuration parameter instead of hardcoding the host, so you can change the host or disable the check without editing your service.

EDIT: complete sample

class MyService
{
    public function __construct($container, $request)
    {
        $this->container = $container;
        $this->request = $request;
    }

    public function doSomething()
    {
        if ( ! $this->checkHostRestrictions()) {
            return;
        }

        // ... do something

    }

    private function checkHostRestrictions() 
    {
        $allowedHost = $this->container->getParameter('myServiceAllowedHost', '');
        if (empty($allowedHost)) {
            // here I assume that if I don't set an allowed host, all are allowed
            // you can easily change the logic
            return true; 
        }

        $clientIp = $this->request->getClientIp();
        if ($clientIp == $allowedHost) {
            return true;
        }

        return false;
    }
}

P.S. of course you may also pass the single parameter and not the full container, but I feel that's not really the topic of the question.

Francesco Abeni
  • 4,190
  • 1
  • 19
  • 30
  • Unless I totally misunderstood your question, Symfony allows you to do it just fine. I edited my answer accordingly. – Francesco Abeni Jul 16 '15 at 11:41
  • That's the way I did it so far. I just think this way is annoying cause you need to implement a logic which has nothing to do with that service.. Sorry if I explained my situation badly. – Thomas CEDRINI Jul 16 '15 at 11:53
  • Oh, I get it now. But in that case the right place for the check is the controller, not the service definition, so even if Symfony would allow you that, it would be "unclean" (IMHO). – Francesco Abeni Jul 16 '15 at 15:19
  • Well... if the service is a symfony event, I cant make the check in the controller. So far I do it insiste the service.. – Thomas CEDRINI Jul 16 '15 at 19:24