47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
|
"""
|
||
|
Middlewares of the require_ipv6 Django app
|
||
|
"""
|
||
|
|
||
|
from django.conf import settings
|
||
|
from django.core.exceptions import MiddlewareNotUsed, SuspiciousOperation
|
||
|
from django.shortcuts import render
|
||
|
from ipware import get_client_ip
|
||
|
import ipaddress
|
||
|
import logging
|
||
|
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
|
||
|
class RequireIPv6Middleware:
|
||
|
"""
|
||
|
A middleware that responds with an error if request is not done via IPv6
|
||
|
"""
|
||
|
|
||
|
def __init__(self, get_response):
|
||
|
# Requirement on IPv6 can be disabled by explicitly using a `True` value
|
||
|
# in setting `REQUIRE_IPV6_DISABLE`
|
||
|
should_disable = getattr(settings, "REQUIRE_IPV6_DISABLE", False) is True
|
||
|
|
||
|
if should_disable:
|
||
|
logger.warning("RequireIPv6 Middleware is disabled per settings.")
|
||
|
raise MiddlewareNotUsed
|
||
|
|
||
|
self.get_response = get_response
|
||
|
|
||
|
def __call__(self, request):
|
||
|
client_ip_address_as_string = get_client_ip(request)[0]
|
||
|
|
||
|
try:
|
||
|
client_ip_address = ipaddress.ip_address(client_ip_address_as_string)
|
||
|
except ValueError:
|
||
|
raise SuspiciousOperation(
|
||
|
"Invalid client IP address: %s" % client_ip_address_as_string
|
||
|
)
|
||
|
|
||
|
if not isinstance(client_ip_address, ipaddress.IPv6Address):
|
||
|
# Client does not use IPv6, render appropriate error page
|
||
|
return render(request, "require_ipv6/error.html", status=400)
|
||
|
|
||
|
# Client uses IPv6, continue processing request
|
||
|
return self.get_response(request)
|