import functools from django.conf import settings def conditional_login_required(view_func): """Skip login_required if client IP is in ALLOWED_CIDR_NETS.""" @functools.wraps(view_func) def wrapper(request, *args, **kwargs): # Get client IP x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[0].strip() else: ip = request.META.get("REMOTE_ADDR", "") # Check if IP is in allowed networks from ipaddress import ip_address, ip_network client_ip = ip_address(ip) for net in getattr(settings, "ALLOWED_CIDR_NETS", []): if client_ip in ip_network(net, strict=False): return view_func(request, *args, **kwargs) # Fall back to login_required from django.contrib.auth.decorators import login_required return login_required(view_func)(request, *args, **kwargs) return wrapper