source: TI12-security/trunk/NDGSecurity/python/Tests/authkitaxexample/openidrelyingpartyax.py @ 7080

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/NDGSecurity/python/Tests/authkitaxexample/openidrelyingpartyax.py@7080
Revision 7080, 6.3 KB checked in by pjkersha, 9 years ago (diff)
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/env python
2
3"""
4This code demonstrates some of the features of an AuthKit based OpenID Relying
5Party with the use of the OpenID Attribute Exchange extensions.
6
7Start the server with:
8
9    python openidrelyingpartyax.py
10   
11Then visit http://localhost:8081/ and you should see the output from the
12``index()`` method which invites you to try the secured link to trigger the
13OpenID Sign In process.  When the Sign In page is displayed enter an OpenID or
14OpenID Provider site address.  To demonstrate the use of attribute exchange
15the OpenID Provider must support their use.  This example requests some of the
16more generic ones such as firstname and lastname but it can modified to suit
17the attributes that a given OpenID Provider can return.
18"""
19from paste import httpexceptions
20
21class NoSuchActionError(httpexceptions.HTTPNotFound):
22    pass
23
24class OpenIDRelyingPartyAXExampleApp:
25    '''OpenID Relying Party using Attribute Exchange extensions'''
26    action = {
27        '/': 'index',
28        '/secure': 'securedPage',
29        '/signedin': 'signedin',
30        '/signout': 'signout'
31    }
32   
33    def __call__(self, environ, start_response):
34        method=OpenIDRelyingPartyAXExampleApp.action.get(environ['PATH_INFO'])
35        if method:
36            return getattr(self, method)(environ, start_response) 
37        else:
38            raise NoSuchActionError()
39
40    def securedPage(self, environ, start_response):
41        user = environ.get('REMOTE_USER')
42        if user is not None:
43            userData = environ.get('REMOTE_USER_DATA', '<empty>')
44            content = ["""<html>
45<head>
46<title>AuthKit Example OpenID Relying Party using Attribute Exchange
47extensions</title>
48</head>
49<body>
50<h1>OpenID Attribute Exchange Secured Page</h1>
51%s
52</body>
53</html>""" % OpenIDRelyingPartyAXExampleApp._loginDetails(environ)]
54
55            start_response('200 OK', [('Content-type','text/html')])
56            return content
57        else:
58            start_response('401 Unauthorized', [('Content-type','text/html')])
59            return "Authorized"
60
61    def signout(self, environ, start_response):
62        start_response('200 OK', [('Content-type','text/html')])
63        return ['''<html>
64<head>
65<title>AuthKit Example OpenID Relying Party using Attribute Exchange
66extensions</title>
67</head>
68<body>
69<h1>Signed Out</h1>
70</body>
71</html>''']
72
73   
74    def index(self, environ, start_response):
75        start_response('200 OK', [('Content-type','text/html')])
76       
77        return ['''<html>
78<head>
79<title>AuthKit Example OpenID Relying Party using Attribute Exchange
80extensions</title>
81</head>
82<body>
83<h1>OpenID Attribute Exchange Example</h1>
84%s
85</body>
86</html>''' % OpenIDRelyingPartyAXExampleApp._loginDetails(environ)]
87       
88    @staticmethod
89    def _loginDetails(environ):
90        '''Convenience utility for displaying login status'''
91        user = environ.get('REMOTE_USER')
92        if user is not None:
93            userData = environ.get('REMOTE_USER_DATA', '<empty>')
94            userDataDict = eval(userData)
95            attrs = userDataDict.get('ax', {})
96            attrTbl = '<table cellspacing="1" cellpadding="3" border="0">\n'
97            for k, v in attrs.iteritems():
98                if k.startswith('value'):
99                    attrTbl += '''  <tr>
100     <td bgcolor="lightgrey">%s</td>
101     <td bgcolor="lightgrey">%s</td>
102  </tr>''' % (k, v)
103 
104            attrTbl += '</table>\n'
105            if '<tr>' in attrTbl:
106                attrMsg = 'with attributes:'
107            else:
108                attrMsg = 'with no attributes retrieved from OpenID Provider.'
109            return '''<p>User signed in:</p>
110<table cellspacing="1" cellpadding="3" border="0">
111  <tr>
112    <td bgcolor="lightgrey">%s</td>
113  </tr>
114</table>
115<p>%s</p>
116%s
117<p><a href="/signout">Sign Out</a></p>''' % (user, attrMsg, attrTbl)
118        else:
119            return '''<p>Access <a href="/secure">Secure page</a> to login
120                   with OpenID</p>'''
121
122
123if __name__ == '__main__':
124    import os
125    from paste.httpserver import serve
126    from authkit.authenticate import middleware
127    from beaker.middleware import SessionMiddleware
128   
129    app = OpenIDRelyingPartyAXExampleApp()
130    app_conf={}
131   
132    # Set AX keywords by setting a type URI keyword of the form
133    # openid_ax_typeuri_<attribute name>. 
134    # * If no alias is set, an attribute name will automatically be allocated
135    # to the value specified. 
136    # * To make the value a required parameter, set
137    # openid_ax_required_<attribute name> to True.  If not set, the parameter
138    # will be optional.
139    # To set array type parameters specify a count to indicate the number of
140    # elements:
141    # openid_ax_count_<attribute name>=10
142    #
143    # or:
144    # openid_ax_count_<attribute name>='unlimited'
145    #
146    # for unlimited array length.
147    thisDir = os.path.abspath(os.path.dirname(__file__))
148    openIDStoreConfigDir = os.path.join(thisDir, 'data', 'openid')
149    app = middleware(app, 
150        setup_method='openid, cookie',
151        cookie_secret='secret string',
152        cookie_signoutpath = '/signout',
153        openid_store_type='file',
154        openid_store_config=openIDStoreConfigDir,
155        openid_session_key='authkit_openid_session_key',
156        openid_session_secret='authkit_openid_session_secret',
157        openid_path_signedin='/',
158        openid_baseurl='http://localhost:8081',
159        openid_ax_typeuri_firstname='http://openid.net/schema/namePerson/first',
160        openid_ax_alias_firstname='firstname',
161        openid_ax_required_firstname=True,
162        openid_ax_typeuri_lastname='http://openid.net/schema/namePerson/last',
163        openid_ax_required_lastname=True,
164        openid_ax_alias_lastname='lastname',
165        openid_ax_typeuri_email='http://openid.net/schema/contact/internet/email',
166        openid_ax_required_email=True,
167        openid_ax_alias_email='email',     
168        openid_ax_typeuri_organization='http://openid.net/schema/company/name',
169        openid_ax_alias_organization='organization',
170#        openid_ax_typeuri_city='http://openid.net/schema/contact/city/home',
171#        openid_ax_alias_city='city',
172#        openid_ax_typeuri_state='http://openid.net/schema/contact/state/home',
173#        openid_ax_alias_state='state',
174#        openid_ax_typeuri_country='http://openid.net/schema/contact/country/home',
175        )
176   
177    app = SessionMiddleware(
178        app, 
179        key='authkit.open_id', 
180        secret='some secret')
181
182    serve(app, host='0.0.0.0', port=8081)
Note: See TracBrowser for help on using the repository browser.