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)
86 """If the request isn't a POST request, raise 405 Method Not Allowed"""
87 if cherrypy.request.method != "POST":
88 raise cherrypy.HTTPError(405,
89 "You must submit this request with POST")
91 cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource', require_POST, priority=150)
93 def remote_user_login():
94 """Get the current user based on the SSL or GSSAPI environment variables"""
95 environ = cherrypy.request.wsgi_environ
96 user = environ.get('REMOTE_USER')
100 cherrypy.request.login = None # clear what cherrypy put there
102 if environ.get('AUTH_TYPE') == 'Negotiate':
103 # Convert the krb5 principal into a krb4 username
104 if not user.endswith('@%s' % config.kerberos.realm):
105 cherrypy.request.login = False # failed to login
107 cherrypy.request.login = user.split('@')[0].replace('/', '.')
109 cherrypy.request.login = user
111 cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_user_login, priority=50)
113 def invirtwebstate_init():
114 """Initialize the cherrypy.request.state object from Invirt"""
115 if not hasattr(cherrypy.request, "state"):
116 cherrypy.request.state = State(cherrypy.request.login)
118 cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
121 _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}