Login

Python fixup handler for Apache

Author:
ofalk
Posted:
June 9, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

If you have another application in the same Apache virtual host and also want to use the authentication from Django - this might help. It uses the Django cookie - so it will not work in another Apache virtual host.

 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import sys
import os
from mod_python import Cookie, apache

os.environ['DJANGO_SETTINGS_MODULE'] = 'YOURAPP.settings'

this=os.path.dirname(__file__)
project=os.path.join(this, "../PATH/TO/YOURAPP")
app=os.path.dirname(project)

sys.path.append(project)
sys.path.append(app)

from mxwnet import settings
from django.contrib.sessions.models import Session

def send_to_login(req):
        # Maybe better use Django settings !?
        req.headers_out['Location'] = "/accounts/login/?next=%s" % req.uri
        return apache.HTTP_MOVED_PERMANENTLY

def fixuphandler(req):
        try:
                raw_cookie = req.headers_in["Cookie"]
        except:
                req.log_error("No cookie within this request\n")
                return send_to_login(req)

        cookies = Cookie.get_cookies(req)
        if cookies.has_key('sessionid'):
                sessionid = cookies['sessionid'].value
                try:
                        s = Session.objects.get(pk=sessionid)
                except:
                        return send_to_login(req)
                try:
                        obj = s.get_decoded()
                except:
                        return send_to_login(req)

                if obj.has_key('_auth_user_id'):
                        return apache.OK
                else:
                        return send_to_login(req)

        else:
                # If the cookie (if any) has no sessionid, return the user to the login box.
                req.log_error("No sessionid within this cookie\n")
                return send_to_login(req)

        # This should never happen. Log it, in case
        req.log_error("ERROR!!!!! We should not reach this point!!!")

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 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

Please login first before commenting.