summaryrefslogtreecommitdiffstats
path: root/ipsilon/util
diff options
context:
space:
mode:
authorPetr Vobornik <pvoborni@redhat.com>2014-01-23 15:00:51 +0100
committerPetr Vobornik <pvoborni@redhat.com>2014-01-24 19:07:05 +0100
commitefaed49f0c8069e3c3ddaf32be7bb8d26c8aae4c (patch)
tree91047b2a197bab1d613aab5028a6399ec67e3ff1 /ipsilon/util
parent96891701df4f1a3c2416663fcc84dde3de3e6bd7 (diff)
downloadipsilon-efaed49f0c8069e3c3ddaf32be7bb8d26c8aae4c.tar.gz
ipsilon-efaed49f0c8069e3c3ddaf32be7bb8d26c8aae4c.tar.xz
ipsilon-efaed49f0c8069e3c3ddaf32be7bb8d26c8aae4c.zip
Rename src package to ipsilon
Diffstat (limited to 'ipsilon/util')
-rw-r--r--ipsilon/util/__init__.py0
-rwxr-xr-xipsilon/util/data.py197
-rwxr-xr-xipsilon/util/page.py56
-rwxr-xr-xipsilon/util/plugin.py69
-rwxr-xr-xipsilon/util/user.py117
5 files changed, 439 insertions, 0 deletions
diff --git a/ipsilon/util/__init__.py b/ipsilon/util/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/ipsilon/util/__init__.py
diff --git a/ipsilon/util/data.py b/ipsilon/util/data.py
new file mode 100755
index 0000000..3fda6d3
--- /dev/null
+++ b/ipsilon/util/data.py
@@ -0,0 +1,197 @@
+#!/usr/bin/python
+#
+# Copyright (C) 2013 Simo Sorce <simo@redhat.com>
+#
+# see file 'COPYING' for use and warranty information
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import os
+import sqlite3
+import cherrypy
+
+class Store(object):
+
+ def __init__(self, path=None):
+ if path is None:
+ self._path = os.getcwd()
+ else:
+ self._path = path
+ self._admin_dbname = self._get_admin_dbname()
+ self._user_dbname = self._get_userprefs_dbname()
+
+ def _get_admin_dbname(self):
+ path = None
+ if 'admin.config.db' in cherrypy.config:
+ path = cherrypy.config['admin.config.db']
+ if not path:
+ path = os.path.join(self._path, 'adminconfig.sqlite')
+ return path
+
+ def _get_userprefs_dbname(self):
+ path = None
+ if 'user.prefs.db' in cherrypy.config:
+ path = cherrypy.config['user.prefs.db']
+ if not path:
+ path = os.path.join(self._path, 'userprefs.sqlite')
+ return path
+
+ def _load_config(self, dbname):
+ con = None
+ rows = []
+ try:
+ con = sqlite3.connect(dbname)
+ cur = con.cursor()
+ cur.executescript("""
+ CREATE TABLE IF NOT EXISTS config(name TEXT, value TEXT)
+ """)
+ cur.execute("SELECT * FROM config")
+ rows = cur.fetchall()
+ con.commit()
+ except sqlite3.Error, e:
+ if con:
+ con.rollback()
+ cherrypy.log.error("Failed to load config: [%s]" % e)
+ finally:
+ if con:
+ con.close()
+
+ conf = {}
+ for row in rows:
+ if row[0] in conf:
+ # multivalued
+ if conf[row[0]] is list:
+ conf[row[0]].append(row[1])
+ else:
+ v = conf[row[0]]
+ conf[row[0]] = [v, row[1]]
+ else:
+ conf[row[0]] = row[1]
+
+ return conf
+
+ def get_admin_config(self):
+ return self._load_config(self._admin_dbname)
+
+ def _load_user_prefs(self, dbname, user):
+ con = None
+ rows = []
+ try:
+ con = sqlite3.connect(dbname)
+ cur = con.cursor()
+ cur.executescript("""
+ CREATE TABLE IF NOT EXISTS users(name TEXT,
+ option TEXT,
+ value TEXT)
+ """)
+ cur.execute("SELECT option, value FROM users "
+ "where name = '%s'" % user)
+ rows = cur.fetchall()
+ con.commit()
+ except sqlite3.Error, e:
+ if con:
+ con.rollback()
+ cherrypy.log.error("Failed to load %s's prefs from "
+ "%s: [%s]" % ( user, dbname, e))
+ finally:
+ if con:
+ con.close()
+
+ conf = {}
+ for row in rows:
+ conf[row[0]] = row[1]
+
+ return conf
+
+ def _get_user_preferences(self, user):
+ return self._load_user_prefs(self._user_dbname, user)
+
+ def _load_login_config(self, dbname):
+ con = None
+ rows = []
+ try:
+ con = sqlite3.connect(dbname)
+ cur = con.cursor()
+ cur.executescript("""
+ CREATE TABLE IF NOT EXISTS login_config(name TEXT,
+ option TEXT,
+ value TEXT)
+ """)
+ cur.execute("SELECT * FROM login_config")
+ rows = cur.fetchall()
+ con.commit()
+ except sqlite3.Error, e:
+ if con:
+ con.rollback()
+ cherrypy.log.error("Failed to load config: [%s]" % e)
+ finally:
+ if con:
+ con.close()
+
+ lpo = []
+ plco = dict()
+ for row in rows:
+ if row[0] == 'global':
+ if row[1] == 'order':
+ lpo = row[2].split(',')
+ continue
+ if row[0] not in plco:
+ # one dict per provider
+ plco[row[0]] = dict()
+
+ conf = plco[row[0]]
+ if row[1] in conf:
+ if conf[row[1]] is list:
+ conf[row[1]].append(row[2])
+ else:
+ v = conf[row[1]]
+ conf[row[1]] = [v, row[2]]
+ else:
+ conf[row[1]] = row[2]
+
+ return (lpo, plco);
+
+ def get_login_config(self):
+ return self._load_login_config(self._admin_dbname)
+
+ def save_login_plugin_config(self, name, options):
+ con = None
+ try:
+ con = sqlite3.connect(self._admin_dbname)
+ cur = con.cursor()
+ curvals = dict()
+ for row in cur.execute(
+ "SELECT option, value FROM login_config WHERE name=?",
+ (name,)):
+ curvals[row[0]] = row[1]
+
+ for o in options:
+ if o in curvals:
+ cur.execute(
+ "UPDATE login_config SET value=? WHERE name=? AND option=?",
+ (options[o], name, o))
+ else:
+ cur.execute(
+ "INSERT INTO login_config VALUES(?,?,?)",
+ (name, o, options[o]))
+
+ con.commit()
+ except sqlite3.Error, e:
+ if con:
+ con.rollback()
+ cherrypy.log.error("Failed to store config: [%s]" % e)
+ raise
+ finally:
+ if con:
+ con.close()
diff --git a/ipsilon/util/page.py b/ipsilon/util/page.py
new file mode 100755
index 0000000..bf30c77
--- /dev/null
+++ b/ipsilon/util/page.py
@@ -0,0 +1,56 @@
+#!/usr/bin/python
+#
+# Copyright (C) 2013 Simo Sorce <simo@redhat.com>
+#
+# see file 'COPYING' for use and warranty information
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+from util import user
+import cherrypy
+
+def protect():
+ user.UserSession().remote_login()
+
+class Page(object):
+ def __init__(self, site):
+ if not 'template_env' in site:
+ raise ValueError('Missing template environment')
+ self._site = site
+ self.basepath = cherrypy.config.get('base.mount', "")
+ self.username = None
+ self.user = None
+
+ def __call__(self, *args, **kwargs):
+ self.user = user.UserSession().get_user()
+
+ if len(args) > 0:
+ op = getattr(self, args[0], None)
+ if callable(op) and getattr(self, args[0]+'.exposed', None):
+ return op(*args[1:], **kwargs)
+ else:
+ op = getattr(self, 'root', None)
+ if callable(op):
+ return op(*args, **kwargs)
+
+ return self.default(*args, **kwargs)
+
+ def _template(self, *args, **kwargs):
+ t = self._site['template_env'].get_template(args[0])
+ return t.render(basepath=self.basepath, user=self.user, **kwargs)
+
+ def default(self, *args, **kwargs):
+ raise cherrypy.HTTPError(404)
+
+ exposed = True
diff --git a/ipsilon/util/plugin.py b/ipsilon/util/plugin.py
new file mode 100755
index 0000000..0c8e466
--- /dev/null
+++ b/ipsilon/util/plugin.py
@@ -0,0 +1,69 @@
+#!/usr/bin/python
+#
+# Copyright (C) 2013 Simo Sorce <simo@redhat.com>
+#
+# see file 'COPYING' for use and warranty information
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import os
+import imp
+import cherrypy
+
+class Plugins(object):
+
+ def __init__(self, path=None):
+ if path is None:
+ self._path = os.getcwd()
+ else:
+ self._path = path
+ self._providers_tree = None
+
+ def _load_class(self, tree, class_type, file_name):
+ cherrypy.log.error('Check module %s for class %s' % (file_name,
+ class_type))
+ name, ext = os.path.splitext(os.path.split(file_name)[-1])
+ try:
+ if ext.lower() == '.py':
+ mod = imp.load_source(name, file_name)
+ #elif ex.lower() == '.pyc':
+ # mod = imp.load_compiled(name, file_name)
+ else:
+ return
+ except Exception, e:
+ cherrypy.log.error('Failed to load "%s" module: [%s]' % (name, e))
+ return
+
+ if hasattr(mod, class_type):
+ instance = getattr(mod, class_type)()
+ public_name = getattr(instance, 'name', name)
+ tree[public_name] = instance
+ cherrypy.log.error('Added module %s as %s' % (name, public_name))
+
+ def _load_classes(self, tree, path, class_type):
+ files = None
+ try:
+ files = os.listdir(path)
+ except Exception, e:
+ cherrypy.log.error('No modules in %s: [%s]' % (path, e))
+ return
+
+ for name in files:
+ filename = os.path.join(path, name)
+ self._load_class(tree, class_type, filename)
+
+ def get_plugins(self, path, class_type):
+ plugins = dict()
+ self._load_classes(plugins, path, class_type)
+ return plugins
diff --git a/ipsilon/util/user.py b/ipsilon/util/user.py
new file mode 100755
index 0000000..f008571
--- /dev/null
+++ b/ipsilon/util/user.py
@@ -0,0 +1,117 @@
+#!/usr/bin/python
+#
+# Copyright (C) 2013 Simo Sorce <simo@redhat.com>
+#
+# see file 'COPYING' for use and warranty information
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+from util import data
+import cherrypy
+
+class Site(object):
+ def __init__(self, value):
+ # implement lookup of sites id for link/name
+ self.link = value
+ self.name = value
+
+class User(object):
+ def __init__(self, username):
+ if username is None:
+ self.name = None
+ self._userdata = dict()
+ else:
+ self._userdata = self._get_user_data(username)
+ self.name = username
+
+ def _get_user_data(self, username):
+ store = data.Store()
+ return store._get_user_preferences(username)
+
+ def reset(self):
+ self.name = None
+ self._userdata = dict()
+
+ @property
+ def is_admin(self):
+ if 'is_admin' in self._userdata:
+ if self._userdata['is_admin'] == '1':
+ return True
+ return False
+
+ @is_admin.setter
+ def is_admin(self, value):
+ if value is True:
+ self._userdata['is_admin'] = '1'
+ else:
+ self._userdata['is_admin'] = '0'
+
+ @property
+ def fullname(self):
+ if 'fullname' in self._userdata:
+ return self._userdata['fullname']
+ else:
+ return self.name
+
+ @fullname.setter
+ def fullname(self, value):
+ self._userdata['fullname'] = value
+
+ @property
+ def sites(self):
+ if 'sites' in self._userdata:
+ d = []
+ for site in self._userdata['sites']:
+ d.append(Site(site))
+ else:
+ return []
+
+ @sites.setter
+ 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 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, destroy old session and regenerate new
+ cherrypy.session.regenerate()
+ 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()