Allow global imports to be specified for Mako templates
[invirt/packages/invirt-web.git] / code / view.py
1 import os
2
3 import cherrypy
4 from mako.template import Template
5 from mako.lookup import TemplateLookup
6 import simplejson
7 import datetime, decimal
8 from invirt.config import structs as config
9 from webcommon import State
10
11 class 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
26 class 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                  imports=[]):
34         # Find the appropriate template lookup.
35         key = (tuple(directories), module_directory)
36         try:
37             lookup = self.lookups[key]
38         except KeyError:
39             lookup = TemplateLookup(directories=directories,
40                                     module_directory=module_directory,
41                                     collection_size=collection_size,
42                                     default_filters=['decode.utf8'],
43                                     input_encoding='utf-8',
44                                     output_encoding='utf-8',
45                                     imports=imports,
46                                     )
47             self.lookups[key] = lookup
48         cherrypy.request.lookup = lookup
49         
50         # Replace the current handler.
51         cherrypy.request.template = t = lookup.get_template(filename)
52         cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
53
54 main = MakoLoader()
55 cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
56
57 class JSONEncoder(simplejson.JSONEncoder):
58         def default(self, obj):
59                 if isinstance(obj, datetime.datetime):
60                         return str(obj)
61                 elif isinstance(obj, decimal.Decimal):
62                         return float(obj)
63                 else:
64                         return simplejson.JSONEncoder.default(self, obj)
65
66 def jsonify_tool_callback(*args, **kwargs):
67     if not cherrypy.request.cached:
68         response = cherrypy.response
69         response.headers['Content-Type'] = 'text/javascript'
70         response.body = JSONEncoder().iterencode(response.body)
71
72 cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
73
74 def external_remote_user_login():
75     pass
76
77 def require_login():
78     """If the user isn't logged in, raise 403 with an error."""
79     if cherrypy.request.login is False:
80         raise cherrypy.HTTPError(403,
81             "You are not authorized to access that resource")
82
83 cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login, priority=150)
84
85 def remote_user_login():
86     """Get the current user based on the SSL or GSSAPI environment variables"""
87     environ = cherrypy.request.wsgi_environ
88     user = environ.get('REMOTE_USER')
89     if user is None:
90         return
91     else:
92         cherrypy.request.login = None # clear what cherrypy put there
93
94     if environ.get('AUTH_TYPE') == 'Negotiate':
95         # Convert the krb5 principal into a krb4 username
96         if not user.endswith('@%s' % config.kerberos.realm):
97             cherrypy.request.login = False # failed to login
98         else:
99             cherrypy.request.login = user.split('@')[0].replace('/', '.')
100     else:
101         cherrypy.request.login = user
102
103 cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_user_login, priority=50)
104
105 def invirtwebstate_init():
106     """Initialize the cherrypy.request.state object from Invirt"""
107     cherrypy.request.state = State(cherrypy.request.login)
108
109 cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
110
111 class View(object):
112     _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}