IP Geolocation¶
DjangoAPI Guard accepts an arbitrary class that implements geolocation and country-based filtering. All it needs is to implement the following protocol:
class GeoIPHandler(Protocol):
@property
def is_initialized(self) -> bool: ...
def initialize(self) -> None: ...
def initialize_redis(self, redis_handler: "RedisManager") -> None: ...
def get_country(self, ip: str) -> str | None: ...
It provides an implementation that uses the ipinfo.io service:
Setup¶
Option 1: Using the built-in IPInfoHandler¶
GUARD_SECURITY_CONFIG = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"),
blocked_countries=["CN", "RU"],
whitelist_countries=["US", "CA"],
block_cloud_providers={"AWS", "GCP"}
)
Option 2: Providing a custom geographical IP handler¶
class CustomGeoIPHandler:
@property
def is_initialized(self) -> bool: ...
def initialize(self) -> None: ...
def initialize_redis(self, redis_handler: "RedisManager") -> None: ...
def get_country(self, ip: str) -> str | None: ...
GUARD_SECURITY_CONFIG = SecurityConfig(
geo_ip_handler=CustomGeoIPHandler(),
blocked_countries=["CN", "RU"],
)
Country Blocking¶
GUARD_SECURITY_CONFIG = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"),
blocked_countries=["CN", "RU", "IR", "KP"]
)
Country Whitelisting¶
GUARD_SECURITY_CONFIG = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"),
whitelist_countries=["US", "CA", "GB", "AU"]
)