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
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.