source: package_branches/invirt-web/cherrypy/code/view.py @ 2398

Last change on this file since 2398 was 2397, checked in by quentin, 15 years ago

Get login information from Apache, if available

File size: 3.7 KB
RevLine 
[2385]1import os
2
3import cherrypy
4from mako.template import Template
5from mako.lookup import TemplateLookup
6import simplejson
7import datetime, decimal
[2397]8from invirt.config import structs as config
[2385]9
10class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
11    """Callable which sets response.body."""
12   
13    def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
14        self.template = template
15        self.next_handler = next_handler
16        self.content_type = content_type
17   
18    def __call__(self):
19        env = globals().copy()
20        env.update(self.next_handler())
21        cherrypy.response.headers['Content-Type'] = self.content_type
22        return self.template.render(**env)
23       
24
25class MakoLoader(object):
26   
27    def __init__(self):
28        self.lookups = {}
29   
30    def __call__(self, filename, directories, module_directory=None,
31                 collection_size=-1, content_type='text/html; charset=utf-8'):
32        # Find the appropriate template lookup.
33        key = (tuple(directories), module_directory)
34        try:
35            lookup = self.lookups[key]
36        except KeyError:
37            lookup = TemplateLookup(directories=directories,
38                                    module_directory=module_directory,
39                                    collection_size=collection_size,
40                                    default_filters=['decode.utf8'],
41                                    input_encoding='utf-8',
42                                    output_encoding='utf-8',
43                                    )
44            self.lookups[key] = lookup
45        cherrypy.request.lookup = lookup
46       
47        # Replace the current handler.
48        cherrypy.request.template = t = lookup.get_template(filename)
49        cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
50
51main = MakoLoader()
52cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
53
54class JSONEncoder(simplejson.JSONEncoder):
55        def default(self, obj):
56                if isinstance(obj, datetime.datetime):
57                        return str(obj)
58                elif isinstance(obj, decimal.Decimal):
59                        return float(obj)
60                else:
61                        return simplejson.JSONEncoder.default(self, obj)
62
63def jsonify_tool_callback(*args, **kwargs):
64    if not cherrypy.request.cached:
65        response = cherrypy.response
66        response.headers['Content-Type'] = 'text/javascript'
67        response.body = JSONEncoder().iterencode(response.body)
68
69cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
70
[2391]71def external_remote_user_login():
72    pass
73
74def require_login():
75    """If the user isn't logged in, raise 403 with an error."""
76    if cherrypy.request.login is False:
77        raise cherrypy.HTTPError(403,
78            "You are not authorized to access that resource")
79
[2397]80cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login, priority=150)
[2391]81
[2397]82def remote_user_login():
83    """Get the current user based on the SSL or GSSAPI environment variables"""
84    environ = cherrypy.request.wsgi_environ
85    user = environ.get('REMOTE_USER')
86    if user is None:
87        return
88    else:
89        cherrypy.request.login = None # clear what cherrypy put there
90
91    if environ.get('AUTH_TYPE') == 'Negotiate':
92        # Convert the krb5 principal into a krb4 username
93        if not user.endswith('@%s' % config.kerberos.realm):
94            cherrypy.request.login = False # failed to login
95        else:
96            cherrypy.request.login = user.split('@')[0].replace('/', '.')
97    else:
98        cherrypy.request.login = user
99
100cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_user_login, priority=50)
101
[2385]102class View(object):
103    _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}
Note: See TracBrowser for help on using the repository browser.