Create a user facility in the session
[cascardo/ipsilon.git] / ipsilon / util / user.py
index 4f7df91..72c5041 100755 (executable)
@@ -45,6 +45,12 @@ class User(object):
         self.name = None
         self._userdata = dict()
 
+    @property
+    def is_anonymous(self):
+        if self.name:
+            return False
+        return True
+
     @property
     def is_admin(self):
         if 'is_admin' in self._userdata:
@@ -87,7 +93,11 @@ class User(object):
 
 class UserSession(object):
     def __init__(self):
-        self.user = cherrypy.session.get('user', None)
+        self.user = self.get_data('user', 'name')
+
+    def _debug(self, fact):
+        if cherrypy.config.get('debug', False):
+            cherrypy.log(fact)
 
     def get_user(self):
         return User(self.user)
@@ -100,10 +110,9 @@ class UserSession(object):
         if self.user == username:
             return
 
-        # REMOTE_USER changed, destroy old session and regenerate new
-        cherrypy.session.regenerate()
-        cherrypy.session['user'] = username
-        cherrypy.session.save()
+        # REMOTE_USER changed, replace user
+        self.nuke_data('user')
+        self.save_data('user', 'name', username)
 
         cherrypy.log('LOGIN SUCCESSFUL: %s', username)
 
@@ -117,3 +126,33 @@ class UserSession(object):
 
         # Destroy current session in all cases
         cherrypy.lib.sessions.expire()
+
+    def save_data(self, facility, name, data):
+        """ Save named data in the session so it can be retrieved later """
+        if facility not in cherrypy.session:
+            cherrypy.session[facility] = dict()
+        cherrypy.session[facility][name] = data
+        cherrypy.session.save()
+        self._debug('Saved session data named [%s:%s]' % (facility, name))
+
+    def get_data(self, facility, name):
+        """ Get named data in the session if available """
+        if facility not in cherrypy.session:
+            return None
+        if name not in cherrypy.session[facility]:
+            return None
+        return cherrypy.session[facility][name]
+
+    def nuke_data(self, facility, name=None):
+        if facility not in cherrypy.session:
+            return
+        if name:
+            if name not in cherrypy.session[facility]:
+                return
+            cherrypy.session[facility][name] = None
+            del cherrypy.session[facility][name]
+            self._debug('Nuked session data named [%s:%s]' % (facility, name))
+        else:
+            del cherrypy.session[facility]
+            self._debug('Nuked session facility [%s]' % (facility,))
+        cherrypy.session.save()