root/trunk/rp/trac/infocard_acct/0.11/infocard_acct/session.py @ 1213

Revision 1213, 5.4 kB (checked in by dbuss, 3 years ago)

Trac Tickets #274, #283 and other misc improvements to work with the latest digitalme

  • Property svn:eol-style set to native
Line 
1#  Copyright (c) 2007 Novell, Inc.
2#  All Rights Reserved.
3 
4#  This library is free software; you can redistribute it and/or
5#  modify it under the terms of the GNU Lesser General Public License as
6#  published by the Free Software Foundation; version 2.1 of the license.
7 
8#  This library is distributed in the hope that it will be useful,
9#  but WITHOUT ANY WARRANTY; without even the implied warranty of
10#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11#  GNU Lesser General Public License for more details.
12 
13#  You should have received a copy of the GNU Lesser General Public License
14#  along with this library; if not, contact Novell, Inc.
15 
16#  To contact Novell about this file by physical or electronic mail,
17#  you may find current contact information at www.novell.com
18#
19
20import re
21
22from trac.core import *
23from trac.web.chrome import ITemplateProvider
24from trac.web.main import IRequestHandler
25
26class SecTokenChangeListener(Interface):
27    """Extension point interface for components that require notification when
28    security tokens are used for authentication"""
29
30    def login(req, secToken):
31        """Called when an security token was used to authenticate succesfully"""
32
33    def logout(req):
34        """Called when an logging out"""
35
36
37class SecTokenSessionModule(Component):
38        """Manage the Security Token Listeners"""
39
40        listeners = ExtensionPoint(SecTokenChangeListener)
41
42        def login(self, req, secToken, options = None):
43                """called on succesful login"""
44                for listener in self.listeners:
45#                       self.log.debug('SecTokenSessionModule login : ' + listener.__class__.__name__)
46                        listener.login(req, secToken)
47
48        def logout(self, req, options=None):
49                """called during logout, cleanup any transitory settings"""
50                for listener in self.listeners:
51                        listener.logout(req)
52
53
54class SecTokenPreferences(Component):
55        """An example of proper checking for claims and settig a few select session
56        attributes.   Useful for using security tokens to setup the prefrences for
57        full name and email address"""
58       
59        implements(SecTokenChangeListener)
60
61        def __init__(self):
62                self.overrideSession = self.config.getbool('infocard_acct', 'override_session', True)
63
64        def login(self, req, secToken):
65                """ on login set the email address and name on the session"""
66
67#               self.log.debug('SecTokenPreferences setup %s %s' % (req, req.session))
68                if secToken and req.session:
69                        email = secToken.getAssertion('http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress')
70                        fullname = secToken.getAssertion('http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname')
71                        last =  secToken.getAssertion('http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname')
72
73                        if not fullname:
74                                fullname = ''
75                        if last:
76                                fullname += ' ' + last
77
78#                       self.log.debug('SecTokenPreferences login:  %s, %s' % (email, fullname))
79
80                        #visit should we override or update the email or just set if not set?
81                        if email and (self.overrideSession or not req.session.has_key('email')):
82                                req.session['email'] = email
83                        if fullname and (self.overrideSession or not req.session.has_key('name')):
84                                req.session['name'] = fullname
85
86        def logout(self, req):
87                """On logout we don't attempt to cleanup or change anything,
88                leaving these attributes in place for notification, administration and
89                subsequent authentications which don't use a security token"""
90                pass
91
92
93class SecTokenInfo(Component):
94        """An example of lazy setting of session vars for all claims and metadata
95        found in the security token."""
96       
97        implements(SecTokenChangeListener, ITemplateProvider, IRequestHandler)
98
99        #SecTokenChangeListner functions
100        def login(self, req, secToken):
101                if secToken and req.session:
102                        metaData = secToken.getMetaData()
103                        if metaData:
104                                for key in metaData.keys():
105                                        req.session['tok_meta_'+key] = metaData[key]
106                                req.session['tok_meta'] = ''.join("tok_meta_%s " \
107                                        % (key) for key in metaData.keys())
108                        claims = secToken.getAssertion()
109                        if claims and claims.keys():
110                                for key in claims.keys():
111                                        req.session['tok_claim_'+key] = claims[key]
112                                req.session['tok_claims'] =''.join("tok_claim_%s " \
113                                        % (key) for key in claims.keys())
114
115        def logout(self, req):
116                """On logout we should cleanup all of the garbage so that subsequent
117                sessions don't end up with incorrect data"""
118                meta = req.session.get('tok_meta')
119#               if meta:
120#                       for key in meta.rsplit(' '):
121#                               del req.session[key]
122#                       del req.session['tok_meta']
123#               if req.session.has_key('tok_claims'):
124#                       for key in req.session.get('tok_claims').rsplit(' '):
125#                               del req.session[key]
126#                       del req.session['tok_claims']
127
128    # IRequestHandler methods
129        def match_request(self, req):
130                if re.match(r'/iinfo/?$', req.path_info) is not None:
131                        return True
132
133                return False
134
135        def process_request(self, req):
136                data = {
137                        'title': 'Infocard Session Debug',
138                        'session': req.session,
139                        'tok_claims': req.session.get('tok_claims'),
140                        'tok_meta': req.session.get('tok_meta')
141                }
142                return 'infocard-session-detail.html', data, None
143
144        #ITemplateProvider functions
145        def get_htdocs_dirs(self):
146                """Return the absolute path of a directory containing additional
147                static resources (such as images, style sheets, etc).
148                """
149                from pkg_resources import resource_filename
150                return [('infocard_acct', resource_filename(__name__, 'htdocs')),
151                   ('site', self.env.get_htdocs_dir())]
152
153        def get_templates_dirs(self):
154                """Return the absolute path of the directory containing the provided
155                templates.
156                """
157                from pkg_resources import resource_filename
158                return [resource_filename(__name__, 'templates')]
Note: See TracBrowser for help on using the browser.