From bfe7a0a4c20f2911404f47a673d7c97252424f30 Mon Sep 17 00:00:00 2001 From: mortezaei Date: Thu, 5 Feb 2026 12:49:54 +0330 Subject: [PATCH] Implement Token Authentication in CourseOnlineClassTokenValidateAPIView - Added TokenAuthentication to allow users to authenticate with a token while still permitting access without authentication. - Removed redundant debug print statements related to token validation to streamline the code and improve readability. --- apps/course/views/course.py | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/apps/course/views/course.py b/apps/course/views/course.py index ece8362..e9e8b92 100644 --- a/apps/course/views/course.py +++ b/apps/course/views/course.py @@ -9,6 +9,7 @@ from django.utils import timezone from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import status +from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.models import Token from rest_framework.exceptions import NotFound from rest_framework.filters import SearchFilter @@ -415,6 +416,9 @@ class CourseOnlineClassTokenAPIView(GenericAPIView): class CourseOnlineClassTokenValidateAPIView(GenericAPIView): + # Changed from AllowAny to enable DRF authentication + # Users can still access without auth, but if token is provided, it will be authenticated + authentication_classes = [TokenAuthentication] permission_classes = [AllowAny] serializer_class = OnlineClassTokenVerifySerializer @@ -454,22 +458,6 @@ class CourseOnlineClassTokenValidateAPIView(GenericAPIView): print(f"[Online Validate GET] user={request.user}") print(f"[Online Validate GET] user.is_authenticated={request.user.is_authenticated}") print(f"[Online Validate GET] user.id={request.user.id if request.user.is_authenticated else 'N/A'}") - print(f"[Online Validate GET] Authorization Header={request.META.get('HTTP_AUTHORIZATION', 'NOT FOUND')}") - print(f"[Online Validate GET] All Headers={dict((k, v) for k, v in request.META.items() if k.startswith('HTTP_'))}") - - # Debug: Check if token exists in database - auth_header = request.META.get('HTTP_AUTHORIZATION', '') - if auth_header.startswith('Token '): - token_key = auth_header.split(' ')[1] - try: - from rest_framework.authtoken.models import Token - token_obj = Token.objects.get(key=token_key) - print(f"[Online Validate GET] Token found in DB - user={token_obj.user} user_id={token_obj.user.id}") - except Token.DoesNotExist: - print(f"[Online Validate GET] Token NOT found in DB - token={token_key[:10]}...") - except Exception as e: - print(f"[Online Validate GET] Token check error - {str(e)}") - print("=" * 80) logger.info(f"[Online Validate GET] Request received - slug={slug} user_id={request.user.id if request.user.is_authenticated else 'anonymous'}")