0

I have a tailormade UploadHandler (SDFUploadHandler) which I want to apply to a POST in Django REST framework (DJRF). However, doing:

request.upload_handlers.insert(0, SDFUploadHandler(request, dataset))

doesn't really work as far as I understand from https://stackoverflow.com/a/30875830/214742 because the DJRF checks the csrf token and once the read has been started it is too late to change upload handlers. I also found How do I modify the file upload handlers in a class based View with CSRF middleware? which shows a neat way to circumvent the automatic csrf token checking and then doing it manually which would mean that I could run my UploadHandler. Problem is that my App needs auditing though so I need to know which user actually made the request and since I have disabled authentication in order for this to work I no longer have request.user. Can in a simple way do the authentication manually as well after I have added my upload handler? Or can the UploadHandler be hooked in earlier somehow?

Also, it's not enough for me that a solution just works with Django standard authentication but it needs to be more general because I will be using Keycloak based authentication as well.

Community
  • 1
  • 1
jonalv
  • 5,706
  • 9
  • 45
  • 64

1 Answers1

0

So, I ended up going with the approach of hooking in the UploadHandler in an earlier step. Turns out the APIView class has a method named initialize_request which i tried to overide in my subclass:

class RestDatasets(APIView):

permission_classes = (IsAuthenticated,)
parser_classes = (MultiPartParser,)
serializer_class = DatasetSerializer

def initialize_request(self, request, *args, **kwargs):
    if request.method == 'POST' :
        request.currentDataset = DatasetModel.objects.create()
        request.upload_handlers.insert(0, SDFUploadHandler(request, request.currentDataset))
    return APIView.initialize_request(self, request, *args, **kwargs)

This seems to have been early enough so nothing has tampered with the data and my upload handler is used instead.

jonalv
  • 5,706
  • 9
  • 45
  • 64