Add graphs of network usage by VMs.
[invirt/packages/invirt-web.git] / code / view.py
index e67f710..51f19a5 100644 (file)
@@ -7,12 +7,15 @@ import simplejson
 import datetime, decimal
 from StringIO import StringIO
 from invirt.config import structs as config
+import invirt.database
 from webcommon import State
 
+
 class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
     """Callable which processes a dictionary, returning the rendered body."""
     
-    def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
+    def __init__(self, template, next_handler,
+                 content_type='text/html; charset=utf-8'):
         self.template = template
         self.next_handler = next_handler
         self.content_type = content_type
@@ -50,13 +53,15 @@ class MakoLoader(object):
     def __call__(self, filename, directories, module_directory=None,
                  collection_size=-1, content_type='text/html; charset=utf-8',
                  imports=[]):
-        cherrypy.request.lookup = lookup = self.get_lookup(directories, module_directory,
-                                                           collection_size, imports)
+        cherrypy.request.lookup = lookup = self.get_lookup(
+            directories, module_directory, collection_size, imports)
         cherrypy.request.template = t = lookup.get_template(filename)
-        cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
+        cherrypy.request.handler = MakoHandler(
+            t, cherrypy.request.handler, content_type)
 
 cherrypy.tools.mako = cherrypy.Tool('on_start_resource', MakoLoader())
 
+
 def revertStandardError():
     """Move stderr to stdout, and return the contents of the old stderr."""
     errio = sys.stderr
@@ -66,6 +71,7 @@ def revertStandardError():
     errio.seek(0)
     return errio.read()
 
+
 def catchStderr():
     old_handler = cherrypy.request.handler
     def wrapper(*args, **kwargs):
@@ -81,6 +87,7 @@ def catchStderr():
 
 cherrypy.tools.catch_stderr = cherrypy.Tool('before_handler', catchStderr)
 
+
 class JSONEncoder(simplejson.JSONEncoder):
        def default(self, obj):
                if isinstance(obj, datetime.datetime):
@@ -90,13 +97,16 @@ class JSONEncoder(simplejson.JSONEncoder):
                else:
                        return simplejson.JSONEncoder.default(self, obj)
 
+
 def jsonify_tool_callback(*args, **kwargs):
     if not cherrypy.request.cached:
         response = cherrypy.response
         response.headers['Content-Type'] = 'text/javascript'
         response.body = JSONEncoder().iterencode(response.body)
 
-cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
+cherrypy.tools.jsonify = cherrypy.Tool('before_finalize',
+                                       jsonify_tool_callback, priority=30)
+
 
 def require_login():
     """If the user isn't logged in, raise 403 with an error."""
@@ -104,15 +114,21 @@ def require_login():
         raise cherrypy.HTTPError(403,
             "You are not authorized to access that resource")
 
-cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login, priority=150)
+cherrypy.tools.require_login = cherrypy.Tool('on_start_resource',
+                                             require_login, priority=150)
+
 
 def require_POST():
     """If the request isn't a POST request, raise 405 Method Not Allowed"""
     if cherrypy.request.method != "POST":
         raise cherrypy.HTTPError(405,
                                  "You must submit this request with POST")
+    if not cherrypy.request.headers.get('Referer', '').startswith('https://' + config.web.hostname):
+        raise cherrypy.HTTPError(403, "This form is only usable when submitted from another page on this site. If you receive this message in error, check your browser's Referer settings.")
+
+cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource',
+                                            require_POST, priority=150)
 
-cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource', require_POST, priority=150)
 
 def remote_user_login():
     """Get remote user from SSL or GSSAPI, and store in request object.
@@ -137,14 +153,22 @@ failed login, and is left at None if the user attempted no authentication.
     else:
         cherrypy.request.login = user
 
-cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_user_login, priority=50)
+cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource',
+                                                 remote_user_login, priority=50)
+
 
 def invirtwebstate_init():
     """Initialize the cherrypy.request.state object from Invirt"""
     if not hasattr(cherrypy.request, "state"):
         cherrypy.request.state = State(cherrypy.request.login)
 
-cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
+cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource',
+                                              invirtwebstate_init, priority=100)
+
+
+cherrypy.tools.clear_db_cache = cherrypy.Tool('on_start_resource', invirt.database.clear_cache)
+
 
 class View(object):
-    _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}
+    _cp_config = {'tools.mako.directories':
+                      [os.path.join(os.path.dirname(__file__),'templates')]}