Require login if not in authorized IP range
This commit is contained in:
parent
d59fb154b6
commit
6f67b855ac
4 changed files with 56 additions and 2 deletions
48
photo21/middleware.py
Normal file
48
photo21/middleware.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
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 = ip_network(ip_range)
|
||||
if ip in net:
|
||||
return True
|
||||
return False
|
||||
Loading…
Add table
Add a link
Reference in a new issue