source: TI12-security/trunk/python/ndg.security.server/ndg/security/server/pylons/container/lib/openid_provider_util.py @ 4545

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.server/ndg/security/server/pylons/container/lib/openid_provider_util.py@4545
Revision 4545, 9.7 KB checked in by pjkersha, 12 years ago (diff)

OpenID Provider Authentication interface:

  • added AuthN extension to enable Session Manager based authentication for OpenID Provider.

OpenID Provider, Session Manager and Attribute Authority WSGI filters now integrated running in a single PAste instance.

Line 
1"""NDG Security OpenID Provider Pylons utilities
2
3Includes Pylons based rendering interface for OpenIDProviderMiddleware
4
5NERC Data Grid Project
6
7This software may be distributed under the terms of the Q Public License,
8version 1.0 or later.
9"""
10__author__ = "P J Kershaw"
11__date__ = "14/08/08"
12__copyright__ = "(C) 2008 STFC & NERC"
13__contact__ = "Philip.Kershaw@stfc.ac.uk"
14__revision__ = "$Id$"
15import pylons
16from pylons.templating import Buffet
17from pylons import config
18import ndg.security.server.sso.sso.lib.helpers as h
19import logging
20log = logging.getLogger(__name__)
21
22# Boiler plate to create renderer
23class OpenIDProviderRenderingBuffet(Buffet):
24    def _update_names(self, ns):
25        return ns
26
27try:
28    def_eng = config['buffet.template_engines'][0]
29    buffet = OpenIDProviderRenderingBuffet(
30        def_eng['engine'],
31        template_root=def_eng['template_root'],
32        **def_eng['template_options']
33    )
34   
35    for e in config['buffet.template_engines'][1:]:
36        buffet.prepare(
37            e['engine'],
38            template_root=e['template_root'],
39            alias=e['alias'],
40            **e['template_options']
41        )
42except:
43    templateRoot = 'ndg.security.server.pylons.container.templates'
44    buffet = OpenIDProviderRenderingBuffet('kid', template_root=templateRoot)
45#{'mako.directories': ['/home/pjkersha/workspace/security/python/ndg.security.server/ndg/security/server/pylons/container/templates'],
46#'myghty.component_root': [{'templates': '/home/pjkersha/workspace/security/python/ndg.security.server/ndg/security/server/pylons/container/templates'}],
47#'myghty.data_dir': '/home/pjkersha/workspace/security/python/ndg.security.server/ndg/security/server/pylons/data/templates',
48#'kid.encoding': 'utf-8',
49#'kid.assume_encoding': 'utf-8',
50#'mako.module_directory': '/home/pjkersha/workspace/security/python/ndg.security.server/ndg/security/server/pylons/data/templates',
51#'myghty.allow_globals': ['c', 'g', 'h', 'render', 'request', 'session', 'translator', 'ungettext', '_', 'N_'],
52#'myghty.output_encoding': 'utf-8',
53#'myghty.raise_error': True,
54#'mako.output_encoding': 'utf-8',
55#'mako.filesystem_checks': True}
56
57
58class State:
59    '''Convenience class for passing parameters from rendering interface to
60    individual template files'''
61    def __init__(self, urls={}, session={}):
62        self.title = ''
63        self.xml = ''
64        self.headExtras = ''
65        self.session = session
66        self.loginStatus = True
67        self.urls = urls
68
69import httplib
70
71# Rendering classes for OpenID Provider must derive from generic render
72# interface
73from ndg.security.server.wsgi.openid.provider import RenderingInterface
74
75class OpenIDProviderKidRendering(RenderingInterface):
76    """Provide Kid Templating for OpenID Provider Middleware via Buffet
77    class"""
78   
79    @staticmethod
80    def _render(templateName, **kw):
81        '''Wrapper for Buffet.render'''
82        rendering = buffet.render(template_name=templateName, namespace=kw)
83        return rendering
84   
85    def login(self, environ, start_response, success_to=None, fail_to=None, 
86              msg=''):
87        """Set-up Kid template for OpenID Provider Login"""
88        c = State(urls=self.urls, session=self.session)
89        c.title = "OpenID Login"
90        c.success_to = success_to or self.urls['url_mainpage']
91        c.fail_to = fail_to or self.urls['url_mainpage'] 
92        c.xml = msg
93       
94        response = OpenIDProviderKidRendering._render('ndg.security.login', 
95                                                      c=c, g=config, h=h)
96        start_response('200 OK', 
97                       [('Content-type', 'text/html'+self.charset),
98                        ('Content-length', str(len(response)))])
99        return response
100       
101       
102    def mainPage(self, environ, start_response):
103        """Set-up Kid template for OpenID Provider Login"""
104        c = State(urls=self.urls, session=self.session)
105        c.title = "OpenID Provider"
106        c.headExtras = '<meta http-equiv="x-xrds-location" content="%s"/>' % \
107                        self.urls['url_serveryadis']
108   
109        response = OpenIDProviderKidRendering._render('ndg.security.mainPage', 
110                                                      c=c, g=config, h=h)
111        start_response('200 OK', 
112                       [('Content-type', 'text/html'+self.charset),
113                        ('Content-length', str(len(response)))])
114        return response
115
116    def identityPage(self, environ, start_response):
117        """Render the user's Identity page"""
118        path = environ['PATH_INFO'].rstrip('/')
119        idPath = self.urls['url_id'].replace(self.base_url, '')
120        username = path[len(idPath)+1:]
121        if not username:
122            h.redirect_to(self.urls['url_mainpage'])
123           
124        c = State(urls=self.urls, session=self.session)
125        c.title = "OpenID Identity Page"
126                       
127        link_tag = '<link rel="openid.server" href="%s"/>' % \
128              self.urls['url_openidserver']
129             
130        yadis_loc_tag = '<meta http-equiv="x-xrds-location" content="%s"/>' % \
131            (self.urls['url_yadis']+'/'+username)
132           
133        c.headExtras = link_tag + yadis_loc_tag
134        identityURL = self.base_url + path
135        c.xml = "<b><pre>%s</pre></b>" % identityURL
136       
137        response = OpenIDProviderKidRendering._render(
138                                                'ndg.security.identityPage', 
139                                                c=c, g=config, h=h)   
140        start_response("200 OK", 
141                       [('Content-type', 'text/html'+self.charset),
142                        ('Content-length', str(len(response)))])
143        return response
144
145   
146    def decidePage(self, environ, start_response, oidRequest):
147        """Handle user interaction required before final submit back to Relying
148        Party"""
149        c = State(urls=self.urls, session=self.session)
150        c.title = 'Approve OpenID Request?'
151        c.trust_root = oidRequest.trust_root
152        c.oidRequest = oidRequest
153       
154        response=OpenIDProviderKidRendering._render('ndg.security.decidePage', 
155                                                    c=c, g=config, h=h)
156        start_response("200 OK", 
157                       [('Content-type', 'text/html'+self.charset),
158                        ('Content-length', str(len(response)))])
159        return response
160
161       
162    def errorPage(self, environ, start_response, msg, code=500):
163        c = State(urls=self.urls, session=self.session)
164        c.title = 'Error with OpenID Provider'
165        c.xml = msg
166        start_response('%d %s' % (code, httplib.responses[code]), 
167                       [('Content-type', 'text/html'+self.charset),
168                        ('Content-length', str(len(response)))])
169        response = OpenIDProviderKidRendering._render('ndg.security.error', 
170                                                      c=c, g=config, h=h)
171        return response
172   
173# Earth System Grid interoperability tests
174
175#esgAxAttr = {'urn:esg.security.gateway': 'BADC',
176#        'urn:esg.security.authority': 'group_IPCC_role_default',
177#        'http://axschema.org/namePerson/last': 'UserLastName',
178#        'http://axschema.org/contact/country/home': 'UK',
179#        'http://axschema.org/namePerson/middle': 'UserMiddleName',
180#        'urn:esg.security.uuid': '0123456789abcdef',
181#        'http://axschema.org/namePerson/first': 'UserFirstName',
182#        'http://axschema.org/namePerson/friendly': '',
183#        'http://axschema.org/contact/email': 'tester@test.com',
184#        'urn:esg.security.organization': 'British Atmospheric Data Centre',
185#}
186
187esgAxAttr = {
188 'http://openid.net/schema/contact/state/home': 'Oxfordshire', 
189 'http://openid.net/schema/namePerson/middle': 'George', 
190 'http://openid.net/schema/contact/city/home': 'Didcot', 
191 'http://openid.net/schema/person/guid': '0123456789abcdef', 
192 'http://openid.net/schema/namePerson/friendly': 'username', 
193 'http://openid.net/schema/company/name': 'The British Atmospheric Data Centre', 
194 'http://openid.net/schema/contact/country/home': 'UK', 
195 'http://openid.net/schema/namePerson/first': 'John', 
196 'http://openid.net/schema/namePerson/last': 'Smith', 
197 'http://openid.net/schema/contact/internet/email': 'testABC@rl.ac.uk',
198 'http://www.earthsystemgrid.org/authority': 'group_IPCC_role_default',
199 'http://www.earthsystemgrid.org/gateway': 'BADC',
200}
201esgAxAlias = {
202 'http://openid.net/schema/contact/state/home': 'state', 
203 'http://openid.net/schema/namePerson/middle': 'middlename', 
204 'http://openid.net/schema/contact/city/home': 'city', 
205 'http://openid.net/schema/person/guid': 'uuid', 
206 'http://openid.net/schema/namePerson/friendly': 'username', 
207 'http://openid.net/schema/company/name': 'organization', 
208 'http://openid.net/schema/contact/country/home': 'country', 
209 'http://openid.net/schema/namePerson/first': 'firstname', 
210 'http://openid.net/schema/namePerson/last': 'lastname', 
211 'http://openid.net/schema/contact/internet/email': 'email',
212 'http://www.earthsystemgrid.org/authority': 'authority',
213 'http://www.earthsystemgrid.org/gateway': 'gateway',
214              }
215
216esgSRegAttr = {
217    'nickname':'',
218    'email':'E-mail Address',
219    'country':'UK',
220    'language':'English',
221    'timezone':'BST',
222    }
223
224
225def esgSRegResponseHandler(username):
226    """Interface function to OpenIdProviderMiddleware to set custom attributes
227    """
228    attr = esgSRegAttr.copy()
229#    attr['username'] = username
230    attr['nickname'] = username
231    return attr
232
233def esgAXResponseHandler(axReq, axResp, username): 
234    """Respond to attributes requested by Relying Party via the Attribute
235    Exchange interface"""
236    attr = esgAxAttr.copy()
237    attr['http://openid.net/schema/namePerson/friendly'] = username
238   
239    for typeURI, attrInfo in axReq.requested_attributes.items():
240        # Value input must be list type
241        axResp.setValues(typeURI, [attr[typeURI]])
Note: See TracBrowser for help on using the repository browser.