Skip to content

Commit

Permalink
Add a middleware to detect LD Accept headers
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewgodwin committed Dec 6, 2022
1 parent e2d28a4 commit 9fe2e66
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 12 deletions.
7 changes: 1 addition & 6 deletions activities/views/posts.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,7 @@ def get(self, request, handle, post_id):
self.identity = by_handle_or_404(self.request, handle, local=False)
self.post_obj = get_object_or_404(self.identity.posts, pk=post_id)
# If they're coming in looking for JSON, they want the actor
accept = request.headers.get("accept", "text/html").lower()
if (
"application/json" in accept
or "application/ld" in accept
or "application/activity" in accept
):
if request.ap_json:
# Return post JSON
return self.serve_object()
else:
Expand Down
19 changes: 19 additions & 0 deletions core/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@
from core.models import Config


class AcceptMiddleware:
"""
Detects any Accept headers signifying a fellow AP server is trying to get JSON.
"""

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
accept = request.headers.get("accept", "text/html").lower()
request.ap_json = (
"application/json" in accept
or "application/ld" in accept
or "application/activity" in accept
)
response = self.get_response(request)
return response


class ConfigLoadingMiddleware:
"""
Caches the system config every request
Expand Down
1 change: 1 addition & 0 deletions takahe/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ class Config:
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django_htmx.middleware.HtmxMiddleware",
"core.middleware.AcceptMiddleware",
"core.middleware.ConfigLoadingMiddleware",
"users.middleware.IdentityMiddleware",
]
Expand Down
7 changes: 1 addition & 6 deletions users/views/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,7 @@ def get(self, request, handle):
):
self.identity.transition_perform(IdentityStates.outdated)
# If they're coming in looking for JSON, they want the actor
accept = request.headers.get("accept", "text/html").lower()
if (
"application/json" in accept
or "application/ld" in accept
or "application/activity" in accept
):
if request.ap_json:
# Return actor info
return self.serve_actor(self.identity)
else:
Expand Down

0 comments on commit 9fe2e66

Please sign in to comment.