Refactor: api file endpoint for auth
This commit is contained in:
parent
bd2791c155
commit
91e7ea2e81
5 changed files with 156 additions and 26 deletions
46
backend/api/authentication/middleware.py
Normal file
46
backend/api/authentication/middleware.py
Normal file
|
@ -0,0 +1,46 @@
|
|||
# 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
|
Loading…
Add table
Add a link
Reference in a new issue