Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions blt/middleware/ip_restrict.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ipaddress
import logging

from django.core.cache import cache
from django.db import models, transaction
Expand All @@ -8,10 +9,12 @@

MAX_COUNT = 2147483647

logger = logging.getLogger(__name__)


class IPRestrictMiddleware:
"""
Middleware to restrict access based on client IP addresses and user agents.
Middleware to restrict access based on client IP addresses and user agent.
"""

def __init__(self, get_response):
Expand Down Expand Up @@ -45,8 +48,8 @@ def blocked_ip_network(self):
try:
network = ipaddress.ip_network(range_str, strict=False)
blocked_ip_network.append(network)
except ValueError:
# Log the error or handle it as needed, but skip invalid networks
except ValueError as e:
logger.error(f"Invalid IP network {range_str}: {str(e)}")
continue

return blocked_ip_network
Expand All @@ -70,7 +73,12 @@ def ip_in_range(self, ip, blocked_ip_network):
"""
Check if the IP address is within any of the blocked IP networks.
"""
ip_obj = ipaddress.ip_address(ip)
try:
ip_obj = ipaddress.ip_address(ip)
except ValueError as e:
logger.error(f"Invalid IP address {ip}: {str(e)}")
return False

return any(ip_obj in ip_range for ip_range in blocked_ip_network)

def is_user_agent_blocked(self, user_agent, blocked_agents):
Expand Down
Loading