2021-04-10 08:16:12 +00:00
|
|
|
__package__ = 'archivebox.core'
|
|
|
|
|
2021-09-30 15:40:13 +00:00
|
|
|
import ipaddress
|
2021-04-10 08:16:12 +00:00
|
|
|
from django.utils import timezone
|
2021-09-30 15:40:13 +00:00
|
|
|
from django.contrib.auth.middleware import RemoteUserMiddleware
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2021-04-10 08:16:12 +00:00
|
|
|
|
2024-10-08 06:45:11 +00:00
|
|
|
from archivebox.config.common import SERVER_CONFIG
|
2021-04-10 08:16:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
def detect_timezone(request, activate: bool=True):
|
|
|
|
gmt_offset = (request.COOKIES.get('GMT_OFFSET') or '').strip()
|
|
|
|
tz = None
|
|
|
|
if gmt_offset.replace('-', '').isdigit():
|
|
|
|
tz = timezone.get_fixed_timezone(int(gmt_offset))
|
|
|
|
if activate:
|
|
|
|
timezone.activate(tz)
|
|
|
|
# print('GMT_OFFSET', gmt_offset, tz)
|
|
|
|
return tz
|
|
|
|
|
|
|
|
|
|
|
|
def TimezoneMiddleware(get_response):
|
|
|
|
def middleware(request):
|
|
|
|
detect_timezone(request, activate=True)
|
|
|
|
return get_response(request)
|
|
|
|
|
|
|
|
return middleware
|
|
|
|
|
|
|
|
|
|
|
|
def CacheControlMiddleware(get_response):
|
|
|
|
def middleware(request):
|
|
|
|
response = get_response(request)
|
|
|
|
|
|
|
|
if '/archive/' in request.path or '/static/' in request.path:
|
2024-10-01 06:21:34 +00:00
|
|
|
policy = 'public' if SERVER_CONFIG.PUBLIC_SNAPSHOTS else 'private'
|
2021-04-10 08:16:12 +00:00
|
|
|
response['Cache-Control'] = f'{policy}, max-age=60, stale-while-revalidate=300'
|
|
|
|
# print('Set Cache-Control header to', response['Cache-Control'])
|
|
|
|
return response
|
|
|
|
|
|
|
|
return middleware
|
2021-09-30 15:40:13 +00:00
|
|
|
|
|
|
|
class ReverseProxyAuthMiddleware(RemoteUserMiddleware):
|
2024-10-01 06:21:34 +00:00
|
|
|
header = 'HTTP_{normalized}'.format(normalized=SERVER_CONFIG.REVERSE_PROXY_USER_HEADER.replace('-', '_').upper())
|
2021-09-30 15:40:13 +00:00
|
|
|
|
|
|
|
def process_request(self, request):
|
2024-10-01 06:21:34 +00:00
|
|
|
if SERVER_CONFIG.REVERSE_PROXY_WHITELIST == '':
|
2021-09-30 15:40:13 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
ip = request.META.get('REMOTE_ADDR')
|
|
|
|
|
2024-10-01 06:21:34 +00:00
|
|
|
for cidr in SERVER_CONFIG.REVERSE_PROXY_WHITELIST.split(','):
|
2021-09-30 15:40:13 +00:00
|
|
|
try:
|
|
|
|
network = ipaddress.ip_network(cidr)
|
|
|
|
except ValueError:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"The REVERSE_PROXY_WHITELIST config paramater is in invalid format, or "
|
|
|
|
"contains invalid CIDR. Correct format is a coma-separated list of IPv4/IPv6 CIDRs.")
|
|
|
|
|
|
|
|
if ipaddress.ip_address(ip) in network:
|
|
|
|
return super().process_request(request)
|