Gallery-Archivist/backend/api/authentication/middleware.py

46 lines
1.5 KiB
Python

# api/authentication/middleware.py
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
class JWTParamMiddleware:
"""
Middleware that allows JWT authentication via query parameters.
This middleware extracts a JWT token from a query parameter named 'token'
and authenticates the user if the token is valid.
"""
def __init__(self, get_response):
self.get_response = get_response
self.jwt_auth = JWTAuthentication()
def __call__(self, request):
self._authenticate_token_param(request)
response = self.get_response(request)
return response
def _authenticate_token_param(self, request):
# Don't authenticate if already authenticated via headers
if hasattr(request, "user") and request.user.is_authenticated:
return
# Get token from the query parameter
token = request.GET.get("token")
if not token:
return
# Validate the token
try:
validated_token = self.jwt_auth.get_validated_token(token)
user = self.jwt_auth.get_user(validated_token)
# Set the authenticated user on the request
request.user = user
# Also set auth in DRF format for API views
request._auth = validated_token
except (InvalidToken, TokenError):
# Don't raise exceptions, just leave as anonymous
pass