I have created a custom django middleware and decorator to authenticate the RESTful API that I am developing. Here is the code of the middleware that I have developed:
# myproject/middleware.pyimport jwtfrom django.conf import settingsfrom django.http import JsonResponsefrom users.models import Userclass JWTAuthenticationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): excluded_paths = ['/auth/users/register/', '/auth/users/login/'] if any(request.path.startswith(path) for path in excluded_paths): return self.get_response(request) # Skip JWT validation for excluded paths token = request.COOKIES.get('jwt') if token: try: decoded = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) user = User.objects.get(id=decoded['id']) request.user = user except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, User.DoesNotExist): return JsonResponse({'error': 'Invalid or expired token'}, status=401) else: request.user = None return self.get_response(request)
This is the code for the decorator:
# users/utils.pyfrom functools import wrapsfrom django.http import JsonResponsefrom django.middleware.csrf import CsrfViewMiddlewaredef token_required(view_func): @wraps(view_func) def _wrapped_view(view_class_instance, request, *args, **kwargs): csrf_middleware = CsrfViewMiddleware() # Check CSRF token csrf_error = csrf_middleware.process_view(request, None, (), {}) if csrf_error: return csrf_error if not request.user: return JsonResponse({'error': 'Token is missing or invalid'}, status=401) return view_func(view_class_instance, request, *args, **kwargs) return _wrapped_view
Here is one of the views that are giving the error:
from rest_framework.views import APIViewfrom users.serializers import UserSerializerfrom rest_framework.response import Responsefrom users.models import Userfrom rest_framework.exceptions import AuthenticationFailedimport jwtfrom django.conf import settingsfrom users.utils import token_requiredclass UserView(APIView): @token_required def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated User!') try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed("Token has expired! Login again") user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data)
And the error is this:
MiddlewareMixin.init() missing 1 required positional argument: 'get_response'
I really need help with getting this to work. Versions of Python and Django that I am using are 3.12.3 and 5.0.4 respectively.
I have tried many different solutions but none worked so far. Even ChatGPT isn't able to find the issues in this small piece of code.