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.pyindex 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_typediff --git a/zerver/middleware.py b/zerver/middleware.pyindex 50ac23e95c7..1da7a1c1f2f 100644--- a/zerver/middleware.py+++ b/zerver/middleware.py@@ -33,7 +33,7 @@ from zerver.lib.exceptions import ErrorCode, JsonableError, MissingAuthenticatiofrom zerver.lib.markdown import get_markdown_requests, get_markdown_timefrom zerver.lib.per_request_cache import flush_per_request_cachesfrom zerver.lib.rate_limiter import RateLimitResult-from zerver.lib.request import RequestNotes+from zerver.lib.request import RequestNotes, get_preferred_typefrom 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.#