def add(self, triples): """Write a list of triples in the store""" for t in triples: db.sql( """ insert ignore into rdf_triple(subject, predicate, object) values (%s, %s, %s)""", (t[0], t[1], t[2]))
def cleanup(): """logout testuser and cleanup""" from lib.chai import db db.begin() db.sql("""delete from session where user=%s""", userobj['name']) db.sql("""delete from user where name=%s""", userobj['name']) db.commit()
def update_password(**args): """update user password""" userobj = model.get(dict(type="user", name="any")) db.sql("""update user set password=%s, reset_password_id=NULL where reset_password_id=%s""", \ (userobj.encrypt_password(args['password']), args['requestid'])) return 'ok'
def before_post(self): """set parent and idx in child pages""" if 'subpage' in self.obj: for idx in range(len(self.obj['subpage'])): db.sql("""update page set parent=%s, idx=%s, _updated=%s where name=%s""", \ (self.obj['name'], idx, datetime.datetime.now(), self.obj['subpage'][idx])) del self.obj['subpage']
def rebuild(type): """ rebuld lft, rgt in all elements needs columns `parent` and `idx` """ global all_nodes all_nodes = [] db.sql("update `%s` set lft=0, rgt=0" % type) build(type)
def post_single(obj, action='insert'): """post an object in db, ignore extra columns""" import MySQLdb obj_copy = get_valid_obj(obj) if action=='insert': query = insert_query(obj, obj_copy) else: query = update_query(obj, obj_copy) db.sql(query, tuple(obj_copy.values()))
def post_single(obj, action='insert'): """post an object in db, ignore extra columns""" import MySQLdb obj_copy = get_valid_obj(obj) if action == 'insert': query = insert_query(obj, obj_copy) else: query = update_query(obj, obj_copy) db.sql(query, tuple(obj_copy.values()))
def build(type, name=None): """ update lft, rgt in this node and all children adds the node at the right-most end of the parent take the rgt of parent and add it at rgt - 1 if root, take the last rgt and add +1 """ global all_nodes if not name: name, parent = '', '' else: parent = db.getvalue(type, name, 'parent') all_nodes.append(name) if parent: lft = db.getvalue(type, parent, 'rgt') else: lft = db.sql("select ifnull(max(rgt),0)+1 as lft from `%s`" % type)[0]['lft'] now = datetime.datetime.now() # insert this node db.sql("update `%s` set rgt=rgt+2, _updated=%s where rgt >= %s" % (type, '%s', '%s'), (now, lft)) db.sql("update `%s` set lft=lft+2, _updated=%s where lft >= %s" % (type, '%s', '%s'), (now, lft)) db.sql("update `%s` set lft=%s, rgt=%s, _updated=%s where name=%s" % \ (type, '%s', '%s', '%s', '%s'), \ (lft, lft+1, now, name)) for c in db.sql("""select name from `%s` where ifnull(parent,'')=%s""" % (type, '%s'), name): if c['name'] in all_nodes: raise Exception, '[nestedset] Circular Reference: %s' % c['name'] build(type, c['name'])
def before_get(self): """ load list of child pages in `subpage` and `subpages` load list of ancestors in `ancestors` """ subpages = db.sql(""" select name, label from page where parent=%s order by idx""", self.obj['name']) self.obj['subpage'] = [d['name'] for d in subpages] self.obj['subpages'] = subpages if 'lft' in self.obj and self.obj['lft']: self.obj['ancestors'] = db.sql("""select name, label from page where lft < %s and rgt > %s order by lft""" % (self.obj['lft'], self.obj['rgt']))
def getchildren(node): """get children <ol>""" global all_nodes, level cl = db.sql("""select name, label from page where parent = %s order by idx""", node) if not cl: return None level += 1 out = '\n' + ('\t'*level) + '<ol>' for node in cl: if node['name'] in all_nodes: raise Exception, 'Circular Page Reference' all_nodes.append(node['name']) out += '\n' + ('\t'*(level+1)) + '<li>'+nodehtml(node)+'</li>' out +='\n' + ('\t'*level) + '</ol>' level -= 1 return out
def triples(self, s, p, o=None): """Return matching triples""" cond, values = self.get_matching_conditions(s, p, o) return db.sql("""select `subject`, `predicate`, `object` from rdf_triple where %s""" % ' and '.join(cond), values, as_dict=False)
def before_get(self): """ load list of child pages in `subpage` and `subpages` load list of ancestors in `ancestors` """ subpages = db.sql( """ select name, label from page where parent=%s order by idx""", self.obj['name']) self.obj['subpage'] = [d['name'] for d in subpages] self.obj['subpages'] = subpages if 'lft' in self.obj and self.obj['lft']: self.obj['ancestors'] = db.sql("""select name, label from page where lft < %s and rgt > %s order by lft""" % (self.obj['lft'], self.obj['rgt']))
def get_user_fullname(**args): """get user fullname""" ret = db.sql(""" select ifnull(fullname, name) as fullname from user where reset_password_id=%s""", args['requestid']) if ret: return ret[0]['fullname'] else: return 'bad id'
def test_logout(self): from webob import Request import lib.chai self.test_login() lib.chai.req = Request.blank('server/?_method=lib.chai.session.logout', \ headers=[('Cookie','sid='+self.sid+';')]) session.logout() self.assertFalse(db.sql("""select * from session where user='******'"""))
def forgot_password(**args): """email the user with a unique link to generate the password""" user = db.sql("""select name from user where name=%s or email=%s""", (args['email'], args['email'])) if not user: return 'No such user' userobj = model.get(objstore.get(type="user", name=user[0]['name'])) userobj.request_reset_password() return 'ok'
def mywblist(**args): """get list of my whiteboards and those i am shared""" from lib.chai import sess if sess['user']=='guest': return {"error":"not logged in"} return {'result': db.sql(""" select name, label from whiteboard where owner = %(user)s order by label asc""", sess) + \ db.sql(""" select wb.name, wb.label from whiteboard wb, whiteboarduser wbuser where wbuser.user=%(user)s and wbuser.parent = wb.name order by wb.label asc""", sess), 'user':sess['user']}
def get_user_fullname(**args): """get user fullname""" ret = db.sql( """ select ifnull(fullname, name) as fullname from user where reset_password_id=%s""", args['requestid']) if ret: return ret[0]['fullname'] else: return 'bad id'
def check_allow(self, method): """raise exception if user is not owner or in shared""" from lib.chai import common, db, sess # rest only allowed if owner or shared if sess["user"] == self.obj.get("owner"): return if sess["user"] in [ a["user"] for a in db.sql("select user from whiteboarduser where parent=%s", self.obj["name"]) ]: return raise Exception, "This whiteboard is private"
def _get_obj(type, name): """load an object without any events""" obj = db.sql("select * from `%s` where name=%s" % (type, '%s'), name, as_dict=1) if not obj: return {} else: obj = obj[0] # add "type" property obj['type'] = type load_children(obj, type, name) return obj
def get(): import urllib site_map = '' if getattr(conf, 'app_url', None): # list of all Guest pages (static content) for r in db.sql("""select name, _updated from page where published=1 and name!='index' order by _updated desc"""): page_url = conf.app_url + '?page=' + urllib.quote(r['name']) site_map += link_xml % (page_url, r['_updated'].strftime('%Y-%m-%d')) return frame_xml % site_map
def load_children(obj, ttype, name): """get children rows""" for childtype in children_types(ttype): obj_list = db.sql("""select * from `%s` where parent=%s and parent_type=%s order by idx asc""" % (childtype,'%s','%s'), (name, ttype)) obj[childtype] = [] for child in obj_list: del child['parent'] del child['parent_type'] del child['idx'] if len(child.keys())==1 and 'value' in child: obj[childtype].append(child['value']) else: obj[childtype].append(child)
def load_children(obj, ttype, name): """get children rows""" for childtype in children_types(ttype): obj_list = db.sql( """select * from `%s` where parent=%s and parent_type=%s order by idx asc""" % (childtype, '%s', '%s'), (name, ttype)) obj[childtype] = [] for child in obj_list: del child['parent'] del child['parent_type'] del child['idx'] if len(child.keys()) == 1 and 'value' in child: obj[childtype].append(child['value']) else: obj[childtype].append(child)
def test_login(self): # make a user from webob import Request, Response import lib.chai objstore.insert(type='user', name='test',password='******') lib.chai.req = Request.blank('server/?_method=lib.chai.session.login&user=test&password=pass') lib.chai.res = Response() # login ret = session.login(**lib.chai.req.params) self.sid = lib.chai.res.headers.get('Set-Cookie').split(';')[0].split('=')[1] self.assertTrue(ret['userobj']['name']=='test') self.assertTrue(ret['message']=='ok') self.assertTrue(db.sql("""select * from session where user='******'""")[0]['user']=='test')
def login(**args): """login""" from lib.chai import res import hashlib pwd = db.sql("select password from user where name=%s", (args['user'],)) if pwd: pwd = pwd[0]['password'] if pwd == hashlib.sha256(args.get("password")).hexdigest(): d = dict(type='session', name=new_sid(), user=args['user']) objstore.insert(**d) res.set_cookie('sid', d['name']) d.update({"message":"ok", "userobj":objstore.get(type='user', name=args['user'])}) return d else: return {"error":"Invalid Login"}
def make(): import os from lib.chai import db messages = [] container = '<div class="main container">' pages_path = os.path.join(os.path.dirname(__file__), '../../../pages') with open( os.path.join(os.path.dirname(__file__), '../../..', 'template.html'), 'r') as f: index_html = f.read() index_html = index_html.split(container) if len(index_html) != 2: return "%s not found" % container for page in db.sql("select * from page", as_dict=1): html = index_html[0] + container +\ '\n<!-- generated via pages.py -->' +\ ('\n<div class="content active" id="%s">' % page['name']) +\ '\n' + page.get('html') +\ (page.get('css') and '\n<style>\n%s\n</style>' % page['css'] or '') +\ (page.get('js') and '\n<script>\n%s\n</script>' % page['js'] or '') +\ '\n</div>\n' +\ index_html[1] # title html = html.split('<title>') html = html[0] +\ '<title>' + page.get('label', page.get('name')) + '</title>' +\ html[1].split('</title>')[1] with open(os.path.join(pages_path, page['name'] + '.html'), 'w') as f: f.write(html) messages.append("wrote %s %sk" % (page['name'] + '.html', len(html) / 1024)) return messages
def login(**args): """login""" from lib.chai import res import hashlib pwd = db.sql("select password from user where name=%s", (args['user'], )) if pwd: pwd = pwd[0]['password'] if pwd == hashlib.sha256(args.get("password")).hexdigest(): d = dict(type='session', name=new_sid(), user=args['user']) objstore.insert(**d) res.set_cookie('sid', d['name']) d.update({ "message": "ok", "userobj": objstore.get(type='user', name=args['user']) }) return d else: return {"error": "Invalid Login"}
def test_login(self): # make a user from webob import Request, Response import lib.chai objstore.insert(type='user', name='test', password='******') lib.chai.req = Request.blank( 'server/?_method=lib.chai.session.login&user=test&password=pass') lib.chai.res = Response() # login ret = session.login(**lib.chai.req.params) self.sid = lib.chai.res.headers.get('Set-Cookie').split(';')[0].split( '=')[1] self.assertTrue(ret['userobj']['name'] == 'test') self.assertTrue(ret['message'] == 'ok') self.assertTrue( db.sql("""select * from session where user='******'""")[0]['user'] == 'test')
def make(): import os from lib.chai import db messages = [] container = '<div class="main container">' pages_path = os.path.join(os.path.dirname(__file__), '../../../pages') with open(os.path.join(os.path.dirname(__file__), '../../..', 'template.html'),'r') as f: index_html = f.read() index_html = index_html.split(container) if len(index_html)!=2: return "%s not found" % container for page in db.sql("select * from page", as_dict=1): html = index_html[0] + container +\ '\n<!-- generated via pages.py -->' +\ ('\n<div class="content active" id="%s">' % page['name']) +\ '\n' + page.get('html') +\ (page.get('css') and '\n<style>\n%s\n</style>' % page['css'] or '') +\ (page.get('js') and '\n<script>\n%s\n</script>' % page['js'] or '') +\ '\n</div>\n' +\ index_html[1] # title html = html.split('<title>') html = html[0] +\ '<title>' + page.get('label', page.get('name')) + '</title>' +\ html[1].split('</title>')[1] with open(os.path.join(pages_path, page['name'] + '.html'), 'w') as f: f.write(html) messages.append("wrote %s %sk" % (page['name'] + '.html', len(html)/1024)) return messages
def get(**args): """ execute a select query Parameters: type columns = "a,b,c" filters = [["a","=","5"],] order_by = "a asc" limit = "20, 20" """ import json if 'json' in args: args.update(json.loads(args['json'])) if 'order_by' in args: args['order_by'] = ' order by ' + args['order_by'] if 'limit' in args: args['limit'] = ' limit ' + args['limit'] args.setdefault('order_by','') args.setdefault('limit','') args.setdefault('conditions','') args.setdefault('values', ()) # conditions if 'filters' in args: if typemethod(args['filters']) in (str, unicode): args['filters'] = json.loads(args['filters']) args['conditions'] = 'where ' + \ ' and '.join(['`%s` %s %s' % (f[0], f[1], '%s') for f in args['filters']]) args['values'] = tuple([f[2] for f in args['filters']]) return {"result": db.sql("""select %(columns)s from `%(type)s` %(conditions)s %(order_by)s %(limit)s""" % args, args['values'], as_dict=1)}
def get(): """generate""" items = [] if getattr(conf, 'app_url', None): # list of all Guest pages (static content) for r in db.sql("""select name, label, _updated from page where published=1 and name!='index' order by _updated desc"""): link = conf.app_url + '?page=' + urllib.quote(r['name']) items.append( rssgen.RSS2(title=r['label'], link=link, description=r.get('description', ''), pubDate=r['_updated'])) rss = rssgen.RSS2(title=conf.app_title, link=conf.app_url, description=getattr(conf, 'description', ''), lastBuildDate=datetime.datetime.utcnow(), items=items) return rss.to_xml()
def get(): """generate""" items = [] if getattr(conf, 'app_url', None): # list of all Guest pages (static content) for r in db.sql("""select name, label, _updated from page where published=1 and name!='index' order by _updated desc"""): link = conf.app_url + '?page=' + urllib.quote(r['name']) items.append(rssgen.RSS2( title = r['label'], link = link, description = r.get('description', ''), pubDate = r['_updated'] )) rss = rssgen.RSS2( title=conf.app_title, link=conf.app_url, description = getattr(conf, 'description', ''), lastBuildDate = datetime.datetime.utcnow(), items = items) return rss.to_xml()
def delete_children(parenttype, parent): """delete all children of the given object""" for child_tab in children_types(parenttype): db.sql("""delete from `%s` where parent=%s and parent_type=%s""" \ % (child_tab,'%s','%s'), (parent, parenttype))
def test_delete(self): self.test_insert() objstore.delete(type="user", name="testuser") self.assertFalse( db.sql("""select * from user where name='testuser'"""))
def test_insert(self): objstore.insert(type="user", name="testuser", email="testmail") obj = db.sql("""select * from user where name='testuser'""")[0] self.assertTrue(obj['email'] == 'testmail')
def children_types(parenttype): """get children types for parent type from table `_parent_child`""" return [c['child'] for c in \ db.sql("select child from _parent_child where parent=%s", parenttype)]
def test_delete(self): self.test_get() rdfstore.delete(name='o1') self.assertFalse( db.sql("select * from rdf_triple where subject=%s", 'o1'))
def delete_obj(type, name): """delete object and its children""" db.sql("""delete from `%s` where name=%s""" % (type, '%s'), name) delete_children(type, name)
def exists(obj): """check exists by name""" if obj.get('name') and obj.get('type'): return db.sql("select name from `%s` where name=%s" % \ (obj['type'],'%s'), obj['name'])
def logout(**args): """logout""" from lib.chai import req user = db.sql("""select user from session where name=%s""", req.cookies['sid'])[0]['user'] db.sql("delete from session where user=%s", user)
def remove(self, s, p, o): """Remove matching triples""" cond, values = self.get_matching_conditions(s, p, o) return db.sql("""delete from rdf_triple where %s""" % \ ' and '.join(cond), values)
def test_delete(self): self.test_insert() objstore.delete(type="user", name="testuser") self.assertFalse(db.sql("""select * from user where name='testuser'"""))
def tearDown(self): # cleanup objstore.delete(type='user', name='test') db.sql("""delete from session where user='******'""") db.rollback()
def test_delete(self): self.test_get() rdfstore.delete(name="o1") self.assertFalse(db.sql("select * from rdf_triple where subject=%s", "o1"))