Login

Use the WSGIAccessScript Directive to secure static files based on the Django session

Author:
LuckiDog
Posted:
May 17, 2011
Language:
Python
Version:
1.3
Tags:
django apache mod_wsgi secure static files
Score:
2 (after 2 ratings)

Add this to your apache config:

<Directory /path/to/media> WSGIAccessScript /path/to/access.wsgi </Directory>

Save the snippet as access.wsgi. Set up the paths, and do some authorization checking.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import os, sys
import site

sys.path = ['<Dir holding Django app>'] + sys.path
site.addsitedir('<Virtualenv root>/lib/python2.6/site-packages')
sys.stdout = sys.stderr
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_site.settings'

from django import db
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.auth.models import User
from django.core.handlers.wsgi import WSGIRequest

def allow_access(environ, host):
    """
    Authentication handler that checks if user is logged in
    """

    # Fake this, allow_access gets a stripped environ
    environ['wsgi.input'] = None

    request = WSGIRequest(environ)
    errors = environ['wsgi.errors']

    try:
        if <Authorized>:
            return True
        else:
            return False
    except Exception as e:
        errors.write('Exception: %s\n' % e)
        return False

    finally:
        db.connection.close()

More like this

  1. Custom mod_python AuthenHandler by aeby 7 years, 11 months ago
  2. apache authentication via cookies by sean 8 years, 5 months ago
  3. Serve static media files from app/media subdirectory by adamlofts 6 years, 12 months ago
  4. Serve static media and indexes from app directories [Python2.5, Development only] by adamlofts 6 years, 11 months ago
  5. X-Sendfile static file serve view by dokterbob 4 years, 9 months ago

Comments

LuckiDog (on August 17, 2011):

Note, You need mod_wsgi > 3.0 to have access to the Cookies from the provided environ.

#

Please login first before commenting.