Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure static media access in a Django site

I'm building a site where registered users can upload files. Those files are then served via Apache. Only users who are logged in should be able to access those files.

I have read this page but it seems that people would have to log in twice to access both the site and the media, each time using a different type of login box.

Is there a way around this or is there some other way to limit access to static media served by Apache using the Django authentication database?

I'm using mod_python.

EDIT: How I ended up solving this after reading Van Gale's answer and this:

  1. Switched to WSGI.
  2. Installed mod_xsendfile
  3. Moved all public media files into a subfolder in /media/public
  4. Added access to the public folder using an Alias /media/public /var/www.../media/public
  5. Added WSGIScriptAlias /media/protected/ /var/www.../apache/django.wsgi (same handler as for the rest of the site)
  6. Added XSendFile On and XSendFileAllowAbove On
  7. To the Django app I added an urlconf for /media/protected which does basically what's here, only modified for my authentication system. It handles urls such as /media/protected/GROUP_ID/file so that only members of the GROUP can download the files.
like image 752
Tomas Andrle Avatar asked Aug 27 '09 12:08

Tomas Andrle


People also ask

Can Django serve static files in production?

During development, as long as you have DEBUG set to TRUE and you're using the staticfiles app, you can serve up static files using Django's development server. You don't even need to run the collecstatic command.

What is static and media in Django?

Media files are typically user or admin uploadable files. Normally you will want MEDIA_ROOT and STATIC_ROOT to be separate directories. Keep in mind that STATIC_ROOT is where the management command collectstatic will place all the static files it finds.


1 Answers

The usual way to do this is to pass back a special header to the web server.

You can do it with nginx using x-accel-redirect as in this Django snippet.

For Apache, it should be pretty similar using the mod_xsendfile module (discussion and examples on Django users mailing list).

like image 51
Van Gale Avatar answered Oct 08 '22 15:10

Van Gale