Provide basic authentication on the development server
[invirt/packages/invirt-web.git] / code / view.py
index a375a9e..5d4750d 100644 (file)
@@ -5,6 +5,8 @@ from mako.template import Template
 from mako.lookup import TemplateLookup
 import simplejson
 import datetime, decimal
+from invirt.config import structs as config
+from webcommon import State
 
 class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
     """Callable which sets response.body."""
@@ -67,5 +69,42 @@ def jsonify_tool_callback(*args, **kwargs):
 
 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:
+        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)
+
+def remote_user_login():
+    """Get the current user based on the SSL or GSSAPI environment variables"""
+    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):
+            cherrypy.request.login = False # failed to login
+        else:
+            cherrypy.request.login = user.split('@')[0].replace('/', '.')
+    else:
+        cherrypy.request.login = user
+
+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"""
+    cherrypy.request.state = State(cherrypy.request.login)
+
+cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
+
 class View(object):
     _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}