Refactor token authentication: streamline bearer token validation and improve error handling
This commit is contained in:
+9
-5
@@ -16,8 +16,8 @@ from pydicom.errors import InvalidDicomError
|
|||||||
from generic.decorators import check_user_in_group
|
from generic.decorators import check_user_in_group
|
||||||
from generic.constants import Group
|
from generic.constants import Group
|
||||||
|
|
||||||
from ninja.security import django_auth
|
from ninja.security import django_auth, HttpBearer
|
||||||
from ninja.security import HttpBearer, HttpError
|
from ninja.errors import HttpError
|
||||||
|
|
||||||
from ninja import NinjaAPI, File
|
from ninja import NinjaAPI, File
|
||||||
from ninja.files import UploadedFile
|
from ninja.files import UploadedFile
|
||||||
@@ -26,7 +26,6 @@ import secrets
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.contrib.auth import authenticate
|
from django.contrib.auth import authenticate
|
||||||
from django.views.decorators.csrf import csrf_exempt
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
from django.views.decorators.csrf import csrf_exempt
|
|
||||||
from django.middleware.csrf import CsrfViewMiddleware
|
from django.middleware.csrf import CsrfViewMiddleware
|
||||||
|
|
||||||
from generic.models import Examination, Modality
|
from generic.models import Examination, Modality
|
||||||
@@ -420,10 +419,15 @@ def token_check(request):
|
|||||||
auth = request.META.get("HTTP_AUTHORIZATION")
|
auth = request.META.get("HTTP_AUTHORIZATION")
|
||||||
token_obj = None
|
token_obj = None
|
||||||
|
|
||||||
# If header present, try TokenAuth path (this will set request.api_token)
|
# If header present, validate bearer token explicitly
|
||||||
if auth:
|
if auth:
|
||||||
|
parts = auth.split()
|
||||||
|
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||||
|
return JsonResponse({"valid": False}, status=401)
|
||||||
|
token = parts[1]
|
||||||
try:
|
try:
|
||||||
user = TokenAuth()(request)
|
bearer = BearerAuth()
|
||||||
|
user = bearer.authenticate(request, token)
|
||||||
token_obj = getattr(request, "api_token", None)
|
token_obj = getattr(request, "api_token", None)
|
||||||
except HttpError:
|
except HttpError:
|
||||||
return JsonResponse({"valid": False}, status=401)
|
return JsonResponse({"valid": False}, status=401)
|
||||||
|
|||||||
Reference in New Issue
Block a user