Add way to tell if the session is anonymous
[cascardo/ipsilon.git] / ipsilon / util / user.py
index ccca9fb..387df11 100755 (executable)
@@ -18,6 +18,7 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 from ipsilon.util.data import Store
+import cherrypy
 
 
 class Site(object):
@@ -40,6 +41,16 @@ class User(object):
         store = Store()
         return store.get_user_preferences(username)
 
+    def reset(self):
+        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:
@@ -78,3 +89,66 @@ class User(object):
     def sites(self):
         #TODO: implement setting sites via the user object ?
         raise AttributeError
+
+
+class UserSession(object):
+    def __init__(self):
+        self.user = cherrypy.session.get('user', None)
+
+    def _debug(self, fact):
+        if cherrypy.config.get('debug', False):
+            cherrypy.log(fact)
+
+    def get_user(self):
+        return User(self.user)
+
+    def remote_login(self):
+        if cherrypy.request.login:
+            return self.login(cherrypy.request.login)
+
+    def login(self, username):
+        if self.user == username:
+            return
+
+        # REMOTE_USER changed, replace user
+        cherrypy.session['user'] = username
+        cherrypy.session.save()
+
+        cherrypy.log('LOGIN SUCCESSFUL: %s', username)
+
+    def logout(self, user):
+        if user is not None:
+            if not type(user) is User:
+                raise TypeError
+            # Completely reset user data
+            cherrypy.log.error('%s %s' % (user.name, user.fullname))
+            user.reset()
+
+        # 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):
+        if facility not in cherrypy.session:
+            return
+        if name not in cherrypy.session[facility]:
+            return
+        cherrypy.session[facility][name] = None
+        del cherrypy.session[facility][name]
+        cherrypy.session.save()
+        self._debug('Nuked session data named [%s:%s]' % (facility, name))