Protect with django the download of a file to a certain user in apache

0

I want to protect a file that resides in an apache so that it can only be downloaded if the user that is logged in is allowed. The case is that the django test server works without problems, but it had not fallen that in Apache this approach does not seem valid and I would like to know if there is any solution with this approach.

The initial idea is for a user to upload an attachment to a folder and only that user can download it.

For this we have the following code:

urls.py
url(r'^documentos/prueba(?P<path>.*)$'.format(settings.MEDIA_URL[1:]), protected_serve_prueba),

views.py
@login_required
def protected_serve_prueba(request, path, document_root='documentos'):
    if _Una_condicion_cualquiera_ == request.user:
        return serve(request, 'prueba'+path, document_root)
    else:
        return HttpResponse("Lo siento, no tiene permiso para acceder a ese archivo") 

In the apache directive

Alias /documentos/prueba /var/www/prueba/documentos/prueba

At the moment I put the directive in the apache it ignores what I put in urls.py and it shows the attachment without verifying if it has permission or not for it.

What solutions can be had to this?

Thanks!

    
asked by Cecilio Alonso 19.10.2017 в 12:09
source

1 answer

0

At the moment I have found a solution that works for me, although surely there are better ones; the idea is to remove the alias in the Apache, which blocks the download requests directly by url.

Then we just have to take the file from the path that we have on the server and return it as content attached to the response if the user meets the conditions we detail to access the file.

In my case only pdf files are treated, so for the time being it is useful to change in the views.py

@login_required
def protected_serve_prueba(request, path):
    if _Una_condicion_cualquiera_ == request.user:
        f = open(ruta_hasta_la_carpeta_adecualda+path, 'rb')
            response = HttpResponse(content=f)
            response['Content-Type'] = 'application/pdf'
            return response
    else:
        return HttpResponse("Lo siento, no tiene permiso para acceder a ese archivo")
    
answered by 19.10.2017 / 16:40
source