mirror of
https://github.com/jointakahe/takahe.git
synced 2024-11-25 08:41:00 +00:00
46947279b0
Add X-Takahe-User and X-Takahe-User-Identity headers to response, when available, to allow for better Nginx log enrichment. Also drop these headers in Nginx so they aren't sent into the world. They probably aren't dangerous since they identfy the users _to themselves_ but strip it for now, just in case.
39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
from django.utils import timezone
|
|
|
|
from users.models import Identity, User
|
|
|
|
|
|
class IdentityMiddleware:
|
|
"""
|
|
Adds a request.identity object which is either the current session's
|
|
identity, or None if they have not picked one yet/it's invalid.
|
|
"""
|
|
|
|
def __init__(self, get_response):
|
|
self.get_response = get_response
|
|
|
|
def __call__(self, request):
|
|
# The API middleware might have set identity already
|
|
if not hasattr(request, "identity"):
|
|
# See if we have one in the session
|
|
identity_id = request.session.get("identity_id")
|
|
if not identity_id:
|
|
request.identity = None
|
|
else:
|
|
# Pull it out of the DB and assign it
|
|
try:
|
|
request.identity = Identity.objects.get(id=identity_id)
|
|
User.objects.filter(pk=request.user.pk).update(
|
|
last_seen=timezone.now()
|
|
)
|
|
except Identity.DoesNotExist:
|
|
request.identity = None
|
|
|
|
response = self.get_response(request)
|
|
|
|
if request.user:
|
|
response.headers["X-Takahe-User"] = str(request.user)
|
|
if request.identity:
|
|
response.headers["X-Takahe-Identity"] = str(request.identity)
|
|
|
|
return response
|