view.py: clean up remote_user_login
[invirt/packages/invirt-web.git] / code / view.py
index e1ba854..e67f710 100644 (file)
@@ -1,15 +1,16 @@
-import os
+import os, sys
 
 import cherrypy
 from mako.template import Template
 from mako.lookup import TemplateLookup
 import simplejson
 import datetime, decimal
 
 import cherrypy
 from mako.template import Template
 from mako.lookup import TemplateLookup
 import simplejson
 import datetime, decimal
+from StringIO import StringIO
 from invirt.config import structs as config
 from webcommon import State
 
 class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
 from invirt.config import structs as config
 from webcommon import State
 
 class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
-    """Callable which sets response.body."""
+    """Callable which processes a dictionary, returning the rendered body."""
     
     def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
         self.template = template
     
     def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
         self.template = template
@@ -27,10 +28,9 @@ class MakoLoader(object):
     
     def __init__(self):
         self.lookups = {}
     
     def __init__(self):
         self.lookups = {}
-    
-    def __call__(self, filename, directories, module_directory=None,
-                 collection_size=-1, content_type='text/html; charset=utf-8',
-                 imports=[]):
+
+    def get_lookup(self, directories, module_directory=None,
+                     collection_size=-1, imports=[], **kwargs):
         # Find the appropriate template lookup.
         key = (tuple(directories), module_directory)
         try:
         # Find the appropriate template lookup.
         key = (tuple(directories), module_directory)
         try:
@@ -45,14 +45,41 @@ class MakoLoader(object):
                                     imports=imports,
                                     )
             self.lookups[key] = lookup
                                     imports=imports,
                                     )
             self.lookups[key] = lookup
-        cherrypy.request.lookup = lookup
-        
-        # Replace the current handler.
+        return lookup
+
+    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.template = t = lookup.get_template(filename)
         cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
 
         cherrypy.request.template = t = lookup.get_template(filename)
         cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
 
-main = MakoLoader()
-cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
+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
+    if not isinstance(errio, StringIO):
+        return ''
+    sys.stderr = sys.stdout
+    errio.seek(0)
+    return errio.read()
+
+def catchStderr():
+    old_handler = cherrypy.request.handler
+    def wrapper(*args, **kwargs):
+        sys.stderr = StringIO()
+        ret = old_handler(*args, **kwargs)
+        e = revertStandardError()
+        if e:
+            if isinstance(ret, dict):
+                ret["error_text"] = e
+        return ret
+    if old_handler:
+        cherrypy.request.handler = wrapper
+
+cherrypy.tools.catch_stderr = cherrypy.Tool('before_handler', catchStderr)
 
 class JSONEncoder(simplejson.JSONEncoder):
        def default(self, obj):
 
 class JSONEncoder(simplejson.JSONEncoder):
        def default(self, obj):
@@ -71,9 +98,6 @@ def jsonify_tool_callback(*args, **kwargs):
 
 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 external_remote_user_login():
-    pass
-
 def require_login():
     """If the user isn't logged in, raise 403 with an error."""
     if cherrypy.request.login is False:
 def require_login():
     """If the user isn't logged in, raise 403 with an error."""
     if cherrypy.request.login is False:
@@ -91,18 +115,23 @@ def require_POST():
 cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource', require_POST, priority=150)
 
 def remote_user_login():
 cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource', require_POST, priority=150)
 
 def remote_user_login():
-    """Get the current user based on the SSL or GSSAPI environment variables"""
+    """Get remote user from SSL or GSSAPI, and store in request object.
+
+Get the current user based on environment variables set by SSL or
+GSSAPI, and store it in the attribute cherrpy.request.login.
+
+Per the CherryPy API (http://www.cherrypy.org/wiki/RequestObject#login),
+the attribute is set to the username on successful login, to False on
+failed login, and is left at None if the user attempted no authentication.
+"""
     environ = cherrypy.request.wsgi_environ
     user = environ.get('REMOTE_USER')
     if user is None:
         return
     environ = cherrypy.request.wsgi_environ
     user = environ.get('REMOTE_USER')
     if user is None:
         return
-    else:
-        cherrypy.request.login = None # clear what cherrypy put there
-
     if environ.get('AUTH_TYPE') == 'Negotiate':
         # Convert the krb5 principal into a krb4 username
         if not user.endswith('@%s' % config.kerberos.realm):
     if environ.get('AUTH_TYPE') == 'Negotiate':
         # Convert the krb5 principal into a krb4 username
         if not user.endswith('@%s' % config.kerberos.realm):
-            cherrypy.request.login = False # failed to login
+            cherrypy.request.login = False # failed to log in
         else:
             cherrypy.request.login = user.split('@')[0].replace('/', '.')
     else:
         else:
             cherrypy.request.login = user.split('@')[0].replace('/', '.')
     else:
@@ -112,7 +141,8 @@ cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_use
 
 def invirtwebstate_init():
     """Initialize the cherrypy.request.state object from Invirt"""
 
 def invirtwebstate_init():
     """Initialize the cherrypy.request.state object from Invirt"""
-    cherrypy.request.state = State(cherrypy.request.login)
+    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)