postgresql.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # ============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. # ============================================================================
  17. # Copyright (C) 2015 Oz Nahum <nahumoz@gmail.com>
  18. # ============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. # ============================================================================
  21. """Postgresql Database implementation."""
  22. import sys
  23. if sys.version_info.major > 2: # pragma: no cover
  24. from urllib.parse import urlparse
  25. else:
  26. from urlparse import urlparse
  27. import psycopg2 as pg
  28. from pwman.data.database import Database, DatabaseException, __DB_FORMAT__
  29. class PostgresqlDatabase(Database):
  30. """
  31. Postgresql Database implementation
  32. This assumes that your database admin has created a pwman database
  33. for you and shared the user name and password with you.
  34. This driver send no clear text on wire. ONLY excrypted stuff is sent
  35. between the client and the server.
  36. Encryption and decryption are happening on your localhost, not on
  37. the Postgresql server.
  38. """
  39. @classmethod
  40. def check_db_version(cls, user, dbname='pwman'): # pragma: no cover
  41. """
  42. Check the database version
  43. """
  44. con = pg.connect("dbname=pwman user=%s" % user)
  45. cur = con.cursor()
  46. try:
  47. cur.execute("SELECT VERSION from DBVERSION")
  48. version = cur.fetchone()
  49. return version
  50. except pg.ProgrammingError:
  51. con.rollback()
  52. raise DatabaseException("Something seems fishy with the DB")
  53. def __init__(self, pgsqluri, dbformat=__DB_FORMAT__):
  54. """
  55. Initialise PostgresqlDatabase instance.
  56. """
  57. self._pgsqluri = pgsqluri
  58. self.dbversion = dbformat
  59. def _open(self):
  60. u = urlparse(self._pgsqluri)
  61. self._con = pg.connect(database=u.path[1:], user=u.username,
  62. password=u.password, host=u.hostname)
  63. self._cur = self._con.cursor()
  64. self._create_tables()
  65. def listnodes(self, filter=None):
  66. if not filter:
  67. sql_all = "SELECT ID FROM NODE"
  68. self._cur.execute(sql_all)
  69. ids = self._cur.fetchall()
  70. return [id[0] for id in ids]
  71. else: # pragma: no cover
  72. tagid = self._get_tag(filter)
  73. if not tagid:
  74. return []
  75. sql_filter = "SELECT NODEID FROM LOOKUP WHERE TAGID = %s "
  76. self._cur.execute(sql_filter, (tagid))
  77. self._con.commit()
  78. ids = self._cur.fetchall()
  79. return [id[0] for id in ids]
  80. def listtags(self):
  81. self._clean_orphans()
  82. get_tags = "select data from tag"
  83. self._cur.execute(get_tags)
  84. tags = self._cur.fetchall()
  85. if tags:
  86. return [t[0] for t in tags]
  87. return []
  88. def _create_tables(self):
  89. try:
  90. self._cur.execute("SELECT 1 from DBVERSION")
  91. version = self._cur.fetchone()
  92. if version:
  93. return
  94. except pg.ProgrammingError:
  95. self._con.rollback()
  96. try:
  97. self._cur.execute("CREATE TABLE NODE(ID SERIAL PRIMARY KEY, "
  98. "USERNAME TEXT NOT NULL, "
  99. "PASSWORD TEXT NOT NULL, "
  100. "URL TEXT NOT NULL, "
  101. "NOTES TEXT NOT NULL"
  102. ")")
  103. self._cur.execute("CREATE TABLE TAG"
  104. "(ID SERIAL PRIMARY KEY,"
  105. "DATA TEXT NOT NULL UNIQUE)")
  106. self._cur.execute("CREATE TABLE LOOKUP ("
  107. "nodeid SERIAL REFERENCES NODE(ID),"
  108. "tagid SERIAL REFERENCES TAG(ID)"
  109. ")")
  110. self._cur.execute("CREATE TABLE CRYPTO "
  111. "(SEED TEXT, DIGEST TEXT)")
  112. self._cur.execute("CREATE TABLE DBVERSION("
  113. "VERSION TEXT NOT NULL DEFAULT {}"
  114. ")".format(__DB_FORMAT__))
  115. self._cur.execute("INSERT INTO DBVERSION VALUES(%s)",
  116. (self.dbversion,))
  117. self._con.commit()
  118. except pg.ProgrammingError:
  119. self._con.rollback()
  120. def fetch_crypto_info(self):
  121. self._cur.execute("SELECT * FROM CRYPTO")
  122. row = self._cur.fetchone()
  123. return row
  124. def save_crypto_info(self, seed, digest):
  125. """save the random seed and the digested key"""
  126. self._cur.execute("DELETE FROM CRYPTO")
  127. self._cur.execute("INSERT INTO CRYPTO VALUES(%s, %s)", (seed, digest))
  128. self._con.commit()
  129. def add_node(self, node):
  130. sql = ("INSERT INTO NODE(USERNAME, PASSWORD, URL, NOTES)"
  131. "VALUES(%s, %s, %s, %s) RETURNING ID")
  132. node_tags = list(node)
  133. node, tags = node_tags[:4], node_tags[-1]
  134. self._cur.execute(sql, (node))
  135. nid = self._cur.fetchone()[0]
  136. self._setnodetags(nid, tags)
  137. self._con.commit()
  138. def _get_tag(self, tagcipher):
  139. sql_search = "SELECT ID FROM TAG WHERE DATA = %s"
  140. self._cur.execute(sql_search, ([tagcipher]))
  141. rv = self._cur.fetchone()
  142. return rv
  143. def _get_or_create_tag(self, tagcipher):
  144. rv = self._get_tag(tagcipher)
  145. if rv:
  146. return rv[0]
  147. else:
  148. sql_insert = "INSERT INTO TAG(DATA) VALUES(%s) RETURNING ID"
  149. self._cur.execute(sql_insert, ([tagcipher]))
  150. rid = self._cur.fetchone()[0]
  151. return rid
  152. def _update_tag_lookup(self, nodeid, tid):
  153. sql_lookup = "INSERT INTO LOOKUP(nodeid, tagid) VALUES(%s, %s)"
  154. self._cur.execute(sql_lookup, (nodeid, tid))
  155. self._con.commit()
  156. def _setnodetags(self, nodeid, tags):
  157. for tag in tags:
  158. tid = self._get_or_create_tag(tag)
  159. self._update_tag_lookup(nodeid, tid)
  160. def _get_node_tags(self, node): # pragma: no cover
  161. sql = "SELECT tagid FROM LOOKUP WHERE NODEID = %s"
  162. tagids = self._cur.execute(sql, (str(node[0]),)).fetchall()
  163. sql = ("SELECT DATA FROM TAG WHERE ID IN (%s)"
  164. "" % ','.join('%%s'*len(tagids)))
  165. tagids = [str(id[0]) for id in tagids]
  166. self._cur.execute(sql, (tagids))
  167. tags = self._cur.fetchall()
  168. for t in tags:
  169. yield t[0]
  170. def getnodes(self, ids):
  171. sql = "SELECT * FROM NODE WHERE ID IN ({})".format(','.join('%s' for
  172. i in ids))
  173. self._cur.execute(sql, (ids))
  174. nodes = self._cur.fetchall()
  175. nodes_w_tags = []
  176. for node in nodes:
  177. #tags = list(self._get_node_tags(node))
  178. tags = []
  179. nodes_w_tags.append(list(node) + tags)
  180. return nodes_w_tags
  181. def editnode(self, nid, **kwargs): # pragma: no cover
  182. tags = kwargs.pop('tags', None)
  183. sql = ("UPDATE NODE SET %s WHERE ID = %%s "
  184. "" % ','.join('%s=%%s' % k for k in list(kwargs)))
  185. self._cur.execute(sql, (list(kwargs.values()) + [nid]))
  186. if tags:
  187. # update all old node entries in lookup
  188. # create new entries
  189. # clean all old tags
  190. sql_clean = "DELETE FROM LOOKUP WHERE NODEID=?"
  191. self._cur.execute(sql_clean, (str(nid),))
  192. self._setnodetags(nid, tags)
  193. self._con.commit()
  194. def removenodes(self, nid):
  195. # shall we do this also in the sqlite driver?
  196. sql_clean = "DELETE FROM LOOKUP WHERE NODEID=%s"
  197. self._cur.execute(sql_clean, nid)
  198. sql_rm = "delete from node where id = %s"
  199. self._cur.execute(sql_rm, nid)
  200. self._con.commit()
  201. def _clean_orphans(self):
  202. clean = ("delete from tag where not exists "
  203. "(select 'x' from lookup l where l.tagid = tag.id)")
  204. self._cur.execute(clean)
  205. self._con.commit()
  206. def savekey(self, key):
  207. salt, digest = key.split('$6$')
  208. sql = "INSERT INTO CRYPTO(SEED, DIGEST) VALUES(%s,%s)"
  209. self._cur.execute("DELETE FROM CRYPTO")
  210. self._cur.execute(sql, (salt, digest))
  211. self._digest = digest.encode('utf-8')
  212. self._salt = salt.encode('utf-8')
  213. self._con.commit()
  214. def loadkey(self):
  215. sql = "SELECT * FROM CRYPTO"
  216. try:
  217. self._cur.execute(sql)
  218. seed, digest = self._cur.fetchone()
  219. return seed + u'$6$' + digest
  220. except TypeError: # pragma: no cover
  221. return None
  222. def close(self): # pragma: no cover
  223. self._clean_orphans()
  224. self._cur.close()
  225. self._con.close()