mirror of
https://git.linux-kernel.at/oliver/ivatar.git
synced 2025-11-12 03:06:24 +00:00
60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
Middleware classes
|
|
"""
|
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
|
from django.middleware.locale import LocaleMiddleware
|
|
|
|
|
|
class CustomLocaleMiddleware(LocaleMiddleware):
|
|
"""
|
|
Middleware that extends LocaleMiddleware to skip Vary header processing for image URLs
|
|
"""
|
|
|
|
def process_response(self, request, response):
|
|
# Check if this is an image-related URL
|
|
path = request.path
|
|
if any(
|
|
path.startswith(prefix)
|
|
for prefix in ["/avatar/", "/gravatarproxy/", "/blueskyproxy/"]
|
|
):
|
|
# Delete Vary from header if exists
|
|
if "Vary" in response:
|
|
del response["Vary"]
|
|
|
|
# Extract hash from URL path for ETag
|
|
# URLs are like /avatar/{hash}, /gravatarproxy/{hash}, /blueskyproxy/{hash}
|
|
path_parts = path.strip("/").split("/")
|
|
if len(path_parts) >= 2:
|
|
hash_value = path_parts[1] # Get the hash part
|
|
response["Etag"] = f'"{hash_value}"'
|
|
else:
|
|
# Fallback to content hash if we can't extract from URL
|
|
response["Etag"] = f'"{hash(response.content)}"'
|
|
|
|
# Skip the parent's process_response to avoid adding Accept-Language to Vary
|
|
return response
|
|
|
|
# For all other URLs, use the parent's behavior
|
|
return super().process_response(request, response)
|
|
|
|
|
|
class MultipleProxyMiddleware(
|
|
MiddlewareMixin
|
|
): # pylint: disable=too-few-public-methods
|
|
"""
|
|
Middleware to rewrite proxy headers for deployments
|
|
with multiple proxies
|
|
"""
|
|
|
|
def process_request(self, request): # pylint: disable=no-self-use
|
|
"""
|
|
Rewrites the proxy headers so that forwarded server is
|
|
used if available.
|
|
"""
|
|
if "HTTP_X_FORWARDED_SERVER" in request.META:
|
|
request.META["HTTP_X_FORWARDED_HOST"] = request.META[
|
|
"HTTP_X_FORWARDED_SERVER"
|
|
]
|