dease dease - 1 year ago 109
Python Question

Restricting access to private file downloads in Django

I have multiple FileFields in my django app, which can belong to different users.
I am looking for a good way to restrict access to files for user who aren't the owner of the file.

What is the best way to achieve this? Any ideas?

Answer Source

Unfortuanately @Mikko's solution cannot actually work on a production environment since django is not designed to serve files. In a production environment files need to be served by your HTTP server (e.g apache, nginx etc) and not by your application/django server (e.g uwsgi, gunicorn, mod_wsgi etc).

That's why restricting file acccess is not very easy: You need a way for your HTTP server to ask the application server if it is ok to serve a file to a specific user requesting it. As you can understand thiss requires modification to both your application and your http server.

The best solution to the above problem is django-sendfile ( which uses the X-SendFile mechanism to implement the above. I'm copying from the project's description:

This is a wrapper around web-server specific methods for sending files to web clients. This is useful when Django needs to check permissions associated files, but does not want to serve the actual bytes of the file itself. i.e. as serving large files is not what Django is made for.

To understand more about the senfile mechanism, please read this answer: Django - Understanding X-Sendfile

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download