4 from mako.template import Template
5 from mako.lookup import TemplateLookup
7 import datetime, decimal
8 from invirt.config import structs as config
9 from webcommon import State
11 class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
12 """Callable which sets response.body."""
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
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)
26 class MakoLoader(object):
31 def __call__(self, filename, directories, module_directory=None,
32 collection_size=-1, content_type='text/html; charset=utf-8',
34 # Find the appropriate template lookup.
35 key = (tuple(directories), module_directory)
37 lookup = self.lookups[key]
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',
47 self.lookups[key] = lookup
48 cherrypy.request.lookup = lookup
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)
55 cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
57 class JSONEncoder(simplejson.JSONEncoder):
58 def default(self, obj):
59 if isinstance(obj, datetime.datetime):
61 elif isinstance(obj, decimal.Decimal):
64 return simplejson.JSONEncoder.default(self, obj)
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)
72 cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
74 def external_remote_user_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")
83 cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login, priority=150)
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')
92 cherrypy.request.login = None # clear what cherrypy put there
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
99 cherrypy.request.login = user.split('@')[0].replace('/', '.')
101 cherrypy.request.login = user
103 cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_user_login, priority=50)
105 def invirtwebstate_init():
106 """Initialize the cherrypy.request.state object from Invirt"""
107 cherrypy.request.state = State(cherrypy.request.login)
109 cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
112 _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}