Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

middleware: Parse Accept header properly.

Anders Kaseorg721f80473655
diff --git a/zerver/lib/request.py b/zerver/lib/request.py
index 303adc9ba26..7c199c9fbbb 100644
--- a/zerver/lib/request.py
+++ b/zerver/lib/request.py
@@ -98,3 +98,22 @@ class RequestVariableConversionError(JsonableError):
arguments_map: dict[str, list[str]] = defaultdict(list)
+
+
+# Equivalent to request.get_preferred_type() in Django 5.2.
+def get_preferred_type(request: HttpRequest, media_types: list[str]) -> str | None:
+ best_type = None
+ best_score = 0.0, True, True
+ for accepted_type in request.accepted_types:
+ score = (
+ float(accepted_type.params.get("q", "1")),
+ accepted_type.main_type != "*",
+ accepted_type.sub_type != "*",
+ )
+ if best_score < score:
+ for media_type in media_types:
+ if accepted_type.match(media_type):
+ best_type = media_type
+ best_score = score
+ break
+ return best_type
diff --git a/zerver/middleware.py b/zerver/middleware.py
index 50ac23e95c7..1da7a1c1f2f 100644
--- a/zerver/middleware.py
+++ b/zerver/middleware.py
@@ -33,7 +33,7 @@ from zerver.lib.exceptions import ErrorCode, JsonableError, MissingAuthenticatio
from zerver.lib.markdown import get_markdown_requests, get_markdown_time
from zerver.lib.per_request_cache import flush_per_request_caches
from zerver.lib.rate_limiter import RateLimitResult
-from zerver.lib.request import RequestNotes
+from zerver.lib.request import RequestNotes, get_preferred_type
from zerver.lib.response import (
AsynchronousResponse,
json_response,
@@ -377,7 +377,7 @@ class LogRequests(MiddlewareMixin):
class JsonErrorHandler(MiddlewareMixin):
def process_exception(self, request: HttpRequest, exception: Exception) -> HttpResponse | None:
if isinstance(exception, MissingAuthenticationError):
- if "text/html" in request.headers.get("Accept", ""):
+ if get_preferred_type(request, ["application/json", "text/html"]) == "text/html":
# If this looks like a request from a top-level page in a
# browser, send the user to the login page.
#