From c00e08d63ebb78d822499c28fdb06c0366434dbc Mon Sep 17 00:00:00 2001 From: Ross Date: Mon, 23 Feb 2026 12:41:58 +0000 Subject: [PATCH] Refactor token authentication: streamline bearer token validation and improve error handling --- atlas/api.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/atlas/api.py b/atlas/api.py index 995180a4..e21f64d8 100644 --- a/atlas/api.py +++ b/atlas/api.py @@ -16,8 +16,8 @@ from pydicom.errors import InvalidDicomError from generic.decorators import check_user_in_group from generic.constants import Group -from ninja.security import django_auth -from ninja.security import HttpBearer, HttpError +from ninja.security import django_auth, HttpBearer +from ninja.errors import HttpError from ninja import NinjaAPI, File from ninja.files import UploadedFile @@ -26,7 +26,6 @@ import secrets from django.utils import timezone from django.contrib.auth import authenticate from django.views.decorators.csrf import csrf_exempt -from django.views.decorators.csrf import csrf_exempt from django.middleware.csrf import CsrfViewMiddleware from generic.models import Examination, Modality @@ -420,10 +419,15 @@ def token_check(request): auth = request.META.get("HTTP_AUTHORIZATION") token_obj = None - # If header present, try TokenAuth path (this will set request.api_token) + # If header present, validate bearer token explicitly if auth: + parts = auth.split() + if len(parts) != 2 or parts[0].lower() != "bearer": + return JsonResponse({"valid": False}, status=401) + token = parts[1] try: - user = TokenAuth()(request) + bearer = BearerAuth() + user = bearer.authenticate(request, token) token_obj = getattr(request, "api_token", None) except HttpError: return JsonResponse({"valid": False}, status=401)