DjangoAuthIntegration: djangoauth.py

File djangoauth.py, 3.9 kB (added by waylan, 5 months ago)

Code updated by Katie Lohrenz and emailed to me on January 10, 2008.

Line 
1 # DjangoAuth plugin
2
3 # Copyright (c) 2007, Waylan Limberg <waylan@gmail.com>
4
5 from trac.core import *
6 from trac.web.chrome import INavigationContributor
7 from trac.web.main import IAuthenticator, IRequestHandler
8 from trac.perm import IPermissionGroupProvider
9 from trac.util import escape, Markup
10 import os
11 import datetime
12
13 class DjangoAuthPlugin(Component):
14     implements(IAuthenticator, IPermissionGroupProvider, \
15                INavigationContributor, IRequestHandler)
16
17     # IAuthenticator methods
18     def authenticate(self, req):
19         authname = None
20         if req.remote_user and (req.remote_user != "anonymous"):
21             authname = req.remote_user
22         elif req.incookie.has_key('sessionid'):
23             cookie = req.incookie['sessionid']
24             sid = cookie.OutputString()[10:-1]
25             authname = self._get_name_from_django(sid)
26         else:
27             authname = req.remote_user
28
29         if authname and self.config.getbool('trac', 'ignore_auth_case'):
30             authname = authname.lower()
31
32         return authname
33
34     # INavigationContributor methods
35     def get_active_navigation_item(self, req):
36         return 'login'
37
38     def get_navigation_items(self, req):
39         if req.authname and req.authname != 'anonymous':
40             yield 'metanav', 'login', 'logged in as "%s"' % req.authname
41             yield 'metanav', 'logout', Markup('<a href="%s">Log-out</a>',
42                     self.config.get('djangoauth', 'logout_url', '#'))
43         else:
44             yield 'metanav', 'login', Markup('<a href="%s">Log-in</a>',
45                     self.config.get('djangoauth', 'login_url', '#'))
46
47     # private methods
48     def _get_name_from_django(self, sessionid):
49         settings = self.config.get('djangoauth', 'django_settings_module')
50        
51         os.environ['DJANGO_SETTINGS_MODULE'] = settings
52         from django.contrib.sessions.models import Session
53         from django.contrib.auth.models import User
54         session = Session.objects.get(pk=sessionid)
55      
56         # Check for stale session
57         if session.expire_date > datetime.datetime.now():
58             data = session.get_decoded()
59
60             if data.has_key('_auth_user_id'):
61                 try:
62                     user = User.objects.get(pk=data['_auth_user_id'])
63                 except User.DoesNotExist:
64                     return None
65
66                 # Check user perms
67                 if user.is_active:
68
69                     if self.config.getbool('djangoauth', 'use_django_perms'):
70                         # make user object available for perm checks later
71                         self.user = user
72
73                     # Update session expire_date
74                     # session.expire_date = datetime.datetime.now()
75                     # session.save() # OperationalError: readonly db??
76
77                     return user.username
78         return None
79  
80     # IPermissionGroupProvider methods
81     def get_permission_groups(self, username):
82         if hasattr(self, 'user') and self.user.username == username:
83             groups = self.user.groups.filter(name__startswith='trac_')
84             return [g.name[5:] for g in groups]
85         else:
86             return []
87
88     # IRequestHandler methods
89     def match_request(self, req):
90         return req.path_info == '/dj'
91
92     def process_request(self, req):
93         req.send_response(200)
94         req.send_header('Content-Type', 'text/plain')
95         req.end_headers()
96         req.write('DjangoAuth is enabled!\n')
97         req.write(str(dir(req))+ '\n')
98         req.write('incookie: ' + str(req.incookie) + '\n')
99         req.write('outcookie: ' + str(req.outcookie) + '\n')
100         req.write('perm: ' + str((req.perm.permissions(),req.perm.perms)) + '\n')
101         req.write('remote_user: ' + str(req.remote_user) + '\n')
102         req.write('server_name: ' + str(req.server_name) + '\n')
103         req.write('session: ' + str(req.session) + '\n')
104         if req.authname:
105             req.write('authname: ' + str(req.authname) + '\n')