photo26/photo21/middleware.py
aeltheos d8853cee1c changed signup to accounts
finished fixing linting
2021-10-07 16:59:16 +02:00

49 lines
1.6 KiB
Python

from django.http import HttpResponseRedirect
from django.conf import settings
import ipaddress
import re
class LoginRequiredMiddleware:
"""
If user is not accessing the site from an authorized IP, force
authentification.
"""
def __init__(self, get_response):
"""Init middleware"""
self.get_response = get_response
self.whitelist_re = re.compile("^/accounts/.*$")
def __call__(self, request):
"""
If user is not authenticated and external, redirect to login view
before calling the view.
"""
if not request.user.is_authenticated and not self.check_ip(request):
if not self.whitelist_re.match(request.path_info):
return HttpResponseRedirect(settings.LOGIN_URL)
response = self.get_response(request)
return response
def check_ip(self, request):
"""
Return true if IP is in authorized range
"""
# Get IP address
if 'HTTP_X_REAL_IP' in request.META:
ip = request.META.get('HTTP_X_REAL_IP')
elif 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META.get('HTTP_X_FORWARDED_FOR').split(', ')[0]
else:
ip = request.META.get('REMOTE_ADDR')
ip = ipaddress.ip_address(ip)
# Check against ranges
if hasattr(settings, 'LOGIN_EXEMPT_IP_RANGE'):
for ip_range in settings.LOGIN_EXEMPT_IP_RANGE:
net = ipaddress.ip_network(ip_range)
if ip in net:
return True
return False