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

Last change on this file since 2400 was 2399, checked in by quentin, 15 years ago

Initialize state object correctly

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