Write handler for create form, and consolidate code to require POST into a CherryPy...
[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 require_POST():
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")
90
91 cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource', require_POST, priority=150)
92
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')
97     if user is None:
98         return
99     else:
100         cherrypy.request.login = None # clear what cherrypy put there
101
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
106         else:
107             cherrypy.request.login = user.split('@')[0].replace('/', '.')
108     else:
109         cherrypy.request.login = user
110
111 cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_user_login, priority=50)
112
113 def invirtwebstate_init():
114     """Initialize the cherrypy.request.state object from Invirt"""
115     cherrypy.request.state = State(cherrypy.request.login)
116
117 cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
118
119 class View(object):
120     _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}