source: TI12-security/trunk/NDGSecurity/python/Tests/httpBasicAuthWSGI/authorize.py @ 7080

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/NDGSecurity/python/Tests/httpBasicAuthWSGI/authorize.py@7080
Revision 7080, 4.3 KB checked in by pjkersha, 9 years ago (diff)
  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/env python
2
3"""
4This code demonstrates some of the features of authkit.authorize.
5
6Start the server with::
7
8    python authorize.py
9   
10Then visit http://localhost:8080/ and you should see the output from the
11``index()`` method which invites you to try some of the links.
12
13Each method linked to is implemented using a different means of checking
14the permission.
15
16In the ``__call__`` method, the code which implements the permission
17attribute checking also demonstrates the use of authorize ``middleware``.
18
19If you sign in with a user other than ``james``, you will be signed in
20but denied access to the resources.
21
22Close your browser to clear the HTTP authentication cache and try the
23example again.
24"""
25
26from authkit.permissions import UserIn
27from authkit.authorize import authorized, authorize, PermissionError
28from authkit.authorize import middleware as authorize_middleware
29from paste import httpexceptions
30
31class NoSuchActionError(httpexceptions.HTTPNotFound):
32    pass
33
34class AuthorizeExampleApp:
35   
36    def __call__(self, environ, start_response):
37        if environ['PATH_INFO'] == '/':
38            method = 'index'
39        else:
40            method = environ['PATH_INFO'].split('/')[1]
41        if not hasattr(self, method):
42            raise NoSuchActionError('No such method')
43        app = getattr(self,method)
44        # This facilitates an alternative way you might want to check permisisons
45        # rather than using an authorize() decorator
46        if hasattr(app, 'permission'):
47            app = authorize_middleware(app, app.permission)
48        return app(environ, start_response) 
49
50    def index(self, environ, start_response):
51        start_response('200 OK', [('Content-type','text/html')])
52        return ['''
53            <html>
54            <head>
55            <title>AuthKit Authorize Example</title>
56            </head>
57            <body>
58            <h1>Authorize Example</h1>
59            <p>Try the following links. You should only be able to sign
60            in as user <tt>james</tt> with the password the same as the
61            username.</p>
62            <ul>
63               <li><a href="/mid_method_test">Mid Method</a></li>
64               <li><a href="/decorator_test">Decorator</a></li>
65               <li><a href="/attribute_test">Attribute (middleware)</a></li>
66            </ul>
67            <p>Once you have signed in you will need to close your
68            browser to clear the authentication cache.</p>
69            </body>
70            </html>
71        ''']
72
73    def mid_method_test(self, environ, start_response):
74        """Authorize using a mid-method permissions check"""
75        if authorized(environ, UserIn(users=['james'])):
76            start_response('200 OK', [('Content-type','text/html')])
77            return ['Access granted to /mid_method_test']
78        else:
79            start_response('200 OK', [('Content-type','text/html')])
80            return ['User is not authorized']
81
82    @authorize(UserIn(users=['james']))
83    def decorator_test(self, environ, start_response):
84        """Authorize using a decorator"""
85        start_response('200 OK', [('Content-type','text/html')])
86        return ['Access granted to /decorator_test']
87
88    def attribute_test(self, environ, start_response):
89        """Authorize using a permission attribute"""
90        start_response('200 OK', [('Content-type','text/html')])
91        return ['Access granted to /attribute_test']
92    attribute_test.permission = UserIn(users=['james'])
93
94if __name__ == '__main__':
95   
96    from paste.httpserver import serve
97    from authkit.authenticate import middleware
98   
99    def valid(environ, username, password):
100        """
101        Sample, very insecure validation function
102        """
103        return username == password
104       
105    app = httpexceptions.make_middleware(AuthorizeExampleApp())
106    app = middleware(
107        app, 
108        setup_method='basic', 
109        basic_realm='Test Realm', 
110        basic_authenticate_function=valid
111    )
112    print """
113Clear the HTTP authentication first by closing your browser if you have been
114testing other basic authentication examples on the same port.
115
116You will be able to sign in as any user as long as the password is the same as
117the username, but all users apart from `james' will be denied access to the
118resources.
119"""
120   
121   
122    serve(app, host='0.0.0.0', port=8080)
Note: See TracBrowser for help on using the repository browser.