Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Geoblocking Bundle Laravel Package

azine/geoblocking-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require azine/geoblocking-bundle

Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

Azine\GeoBlockingBundle\AzineGeoBlockingBundle::class => ['all' => true],
  1. Basic Configuration: Add minimal config to config/packages/azine_geo_blocking.yaml (Symfony 4+) or app/config/config.yml (Symfony 2/3):

    azine_geo_blocking:
        enabled: true
        countries:
            blacklist: ["US", "CN"]  # Block users from these countries
        routes:
            whitelist: ["fos_user_security_login"]  # Allow login route
    
  2. First Use Case:

    • Access a restricted route (e.g., /dashboard) from a blocked country (e.g., US).
    • Verify the accessDenied.html.twig template (located in vendor/azine/geoblocking-bundle/Resources/views/) is rendered.

Implementation Patterns

Core Workflow

  1. Request Handling: The bundle listens to the kernel.request event. For each request:

    • Checks if the route is whitelisted/blacklisted.
    • Determines the visitor’s country via the configured lookup_adapter.
    • Validates against country whitelists/blacklists.
    • Skips blocking for logged-in users (if block_anonymouse_users_only: true).
  2. Integration with FOSUserBundle:

    • Default config assumes FOSUserBundle for authentication.
    • Logged-in users bypass geoblocking unless explicitly configured otherwise.
    • Whitelist login/logout routes by default:
      routes:
          whitelist:
              - fos_user_security_login
              - fos_user_security_login_check
              - fos_user_security_logout
      
  3. Dynamic Route Handling:

    • Use route names (not paths) for whitelists/blacklists:
      routes:
          blacklist:
              - app_homepage  # Route defined in `routing.yml`
      
    • Override the default accessDenied view by specifying a custom Twig template:
      access_denied_view: "AcmeBundle:Page:geoBlocked.html.twig"
      
  4. Cookie-Based Exceptions:

    • Allow temporary access via cookies (e.g., for invited users):
      // Controller
      $response->headers->setCookie(new Cookie("geoblocking_allow_cookie", true, new \DateTime("+2 days")));
      
    • Enable in config:
      allow_by_cookie: true
      
  5. IP Whitelisting:

    • Bypass geoblocking for specific IPs (e.g., crawlers):
      ip_whitelist:
          - "123.45.67.89"
          - "/^192\.168\.\d+\.\d+$/"  # Regex for private networks
      
  6. Search Bot Allowance:

    • Whitelist bot domains (e.g., Googlebot):
      allow_search_bots: true
      search_bot_domains:
          - ".googlebot.com"
      

Gotchas and Tips

Common Pitfalls

  1. GeoIP Module Dependency:

    • Error: geoip_country_code_by_name() not found.
    • Fix: Install the PHP GeoIP extension (pecl install geoip) or use the MaxmindGeoIPBundle:
      lookup_adapter: azine_geo_blocking.maxmind.lookup.adapter
      
      Requires maxmind/geoip and its bundle configuration.
  2. Route Name Mismatches:

    • Error: Blocking doesn’t apply to expected routes.
    • Fix: Verify route names in routes: config match those in routing.yml (use debug:router to list routes).
  3. Logged-In User Bypass:

    • Issue: Logged-in users are blocked unexpectedly.
    • Fix: Ensure block_anonymouse_users_only: true (default) and that the user session is properly authenticated (e.g., FOSUserBundle).
  4. Private IP Handling:

    • Issue: Localhost/private IPs are blocked.
    • Fix: Set allow_private_ips: true (default) or whitelist specific IPs.
  5. Cookie Persistence:

    • Issue: geoblocking_allow_cookie expires too soon.
    • Fix: Adjust the cookie expiry in the controller (e.g., new \DateTime("+7 days")).
  6. Case Sensitivity in Country Codes:

    • Issue: Country codes like "us" vs "US" cause inconsistencies.
    • Fix: Standardize to uppercase (e.g., "US", "CN") in config.

Debugging Tips

  1. Log Blocked Requests: Enable logging to debug blocked requests:

    logBlockedRequests: true
    

    Check Symfony logs (var/log/dev.log) for entries like:

    [GeoBlocking] Blocked request from IP [X.X.X.X] (Country: US) on route [app_homepage].
    
  2. Test with Known IPs: Use services like IP2Location to test with specific country IPs:

    curl -H "X-Forwarded-For: 66.249.64.0" http://your-site.com/dashboard
    
  3. Override Default Views: Copy accessDenied.html.twig to your project (e.g., templates/AzineGeoBlocking/accessDenied.html.twig) to customize without modifying the bundle.

  4. Custom Lookup Adapter: Implement GeoIpLookupAdapterInterface for alternative providers (e.g., AWS Location Service):

    // src/Service/CustomGeoIpAdapter.php
    class CustomGeoIpAdapter implements GeoIpLookupAdapterInterface {
        public function getCountryCodeByIp($ip) {
            // Your logic here (e.g., API call)
            return "US";
        }
    }
    

    Register as a service:

    services:
        azine_geo_blocking.custom.adapter:
            class: App\Service\CustomGeoIpAdapter
            tags: ['azine_geo_blocking.lookup_adapter']
    

    Update config:

    lookup_adapter: azine_geo_blocking.custom.adapter
    

Performance Considerations

  1. GeoIP Lookup Overhead:

    • Caching: Cache country lookups (e.g., using Symfony’s cache) if using a slow provider.
    • Example with Symfony Cache:
      $cache = $this->container->get('cache.app');
      $countryCode = $cache->get($ip, function() use ($ip) {
          return $this->geoIpAdapter->getCountryCodeByIp($ip);
      });
      
  2. Route Matching:

    • Pre-compile route names to avoid runtime lookups:
      $router = $this->container->get('router');
      $routeName = $router->getRouteCollection()->getNameForPath($request->getPathInfo());
      

Extension Points

  1. Event Listeners: Extend functionality by subscribing to azine.geo_blocking.block_request:

    // src/EventListener/CustomGeoBlockListener.php
    class CustomGeoBlockListener {
        public function onBlockRequest(GeoBlockEvent $event) {
            if ($event->isBlocked()) {
                // Custom logic (e.g., redirect to a survey)
                $event->setResponse(new RedirectResponse('/survey'));
            }
        }
    }
    

    Register the listener:

    services:
        App\EventListener\CustomGeoBlockListener:
            tags:
                - { name: kernel.event_listener, event: azine.geo_blocking.block_request, method: onBlockRequest }
    
  2. Dynamic Country Lists: Fetch country whitelists/blacklists from a database or API:

    // Override the bundle's CountryValidator
    class DynamicCountryValidator extends CountryValidator {
        public function isAllowed($countryCode) {
            $allowedCountries = $this->fetchFromDatabase(); // Your logic
            return in_array(strtoupper($countryCode), $allowedCountries);
        }
    }
    

    Replace the default validator in services:

    services:
        azine_geo_blocking.country_validator:
            class: App\Validator\DynamicCountryValidator
            arguments: ['@azine_geo_blocking.country_list']
    
  3. Multi-Tenant Support: Store geoblocking rules per tenant:

    # Per-tenant config (e.g., in a database)
    azine_geo_blocking:
        countries:
            blacklist: "%tenant_blacklist%"  # Resolved via parameter bag
    

    Use Symfony’s parameter bag to inject

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware