postgresql.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 psycopg2 as pg
  23. from pwman.data.database import Database, __DB_FORMAT__
  24. class PostgresqlDatabase(Database):
  25. """
  26. Postgresql Database implementation
  27. This assumes that your database admin has created a pwman database
  28. for you and shared the user name and password with you.
  29. This driver send no clear text on wire. ONLY excrypted stuff is sent
  30. between the client and the server.
  31. Encryption and decryption are happening on your localhost, not on
  32. the Postgresql server.
  33. """
  34. @classmethod
  35. def check_db_version(cls, dburi):
  36. """
  37. Check the database version
  38. """
  39. #if isinstance(dburi, ParseResult):
  40. # con = pg.connect(dburi.geturl())
  41. #else:
  42. con = pg.connect(dburi)
  43. cur = con.cursor()
  44. try:
  45. cur.execute("SELECT VERSION from DBVERSION")
  46. version = cur.fetchone()
  47. con.close()
  48. cur.close()
  49. return version
  50. except pg.ProgrammingError:
  51. con.rollback()
  52. def __init__(self, pgsqluri, dbformat=__DB_FORMAT__):
  53. """
  54. Initialise PostgresqlDatabase instance.
  55. """
  56. self._pgsqluri = pgsqluri
  57. self.dbversion = dbformat
  58. def _open(self):
  59. self._con = pg.connect(self._pgsqluri.geturl())
  60. self._cur = self._con.cursor()
  61. self._create_tables()
  62. def listnodes(self, filter=None):
  63. if not filter:
  64. sql_all = "SELECT ID FROM NODE"
  65. self._cur.execute(sql_all)
  66. ids = self._cur.fetchall()
  67. return [id[0] for id in ids]
  68. else:
  69. tagid = self._get_tag(filter)
  70. if not tagid:
  71. return [] # pragma: no cover
  72. sql_filter = "SELECT NODEID FROM LOOKUP WHERE TAGID = %s "
  73. self._cur.execute(sql_filter, (tagid))
  74. self._con.commit()
  75. ids = self._cur.fetchall()
  76. return [id[0] for id in ids]
  77. def listtags(self):
  78. self._clean_orphans()
  79. get_tags = "select data from tag"
  80. self._cur.execute(get_tags)
  81. tags = self._cur.fetchall()
  82. if tags:
  83. return [t[0] for t in tags]
  84. return [] # pragma: no cover
  85. def _create_tables(self):
  86. try:
  87. self._cur.execute("SELECT 1 from DBVERSION")
  88. version = self._cur.fetchone()
  89. if version:
  90. return
  91. except pg.ProgrammingError:
  92. self._con.rollback()
  93. try:
  94. self._cur.execute("CREATE TABLE NODE(ID SERIAL PRIMARY KEY, "
  95. "USERNAME TEXT NOT NULL, "
  96. "PASSWORD TEXT NOT NULL, "
  97. "URL TEXT NOT NULL, "
  98. "NOTES TEXT NOT NULL"
  99. ")")
  100. self._cur.execute("CREATE TABLE TAG"
  101. "(ID SERIAL PRIMARY KEY,"
  102. "DATA TEXT NOT NULL UNIQUE)")
  103. self._cur.execute("CREATE TABLE LOOKUP ("
  104. "nodeid SERIAL REFERENCES NODE(ID),"
  105. "tagid SERIAL REFERENCES TAG(ID)"
  106. ")")
  107. self._cur.execute("CREATE TABLE CRYPTO "
  108. "(SEED TEXT, DIGEST TEXT)")
  109. self._cur.execute("CREATE TABLE DBVERSION("
  110. "VERSION TEXT NOT NULL DEFAULT {}"
  111. ")".format(__DB_FORMAT__))
  112. self._cur.execute("INSERT INTO DBVERSION VALUES(%s)",
  113. (self.dbversion,))
  114. self._con.commit()
  115. except pg.ProgrammingError: # pragma: no cover
  116. self._con.rollback()
  117. def fetch_crypto_info(self):
  118. self._cur.execute("SELECT * FROM CRYPTO")
  119. row = self._cur.fetchone()
  120. return row
  121. def save_crypto_info(self, seed, digest):
  122. """save the random seed and the digested key"""
  123. self._cur.execute("DELETE FROM CRYPTO")
  124. self._cur.execute("INSERT INTO CRYPTO VALUES(%s, %s)", (seed, digest))
  125. self._con.commit()
  126. def add_node(self, node):
  127. sql = ("INSERT INTO NODE(USERNAME, PASSWORD, URL, NOTES)"
  128. "VALUES(%s, %s, %s, %s) RETURNING ID")
  129. node_tags = list(node)
  130. node, tags = node_tags[:4], node_tags[-1]
  131. self._cur.execute(sql, (node))
  132. nid = self._cur.fetchone()[0]
  133. self._setnodetags(nid, tags)
  134. self._con.commit()
  135. def _get_tag(self, tagcipher):
  136. sql_search = "SELECT ID FROM TAG WHERE DATA = %s"
  137. self._cur.execute(sql_search, ([tagcipher]))
  138. rv = self._cur.fetchone()
  139. return rv
  140. def _get_or_create_tag(self, tagcipher):
  141. rv = self._get_tag(tagcipher)
  142. if rv:
  143. return rv[0]
  144. else:
  145. sql_insert = "INSERT INTO TAG(DATA) VALUES(%s) RETURNING ID"
  146. self._cur.execute(sql_insert, ([tagcipher]))
  147. rid = self._cur.fetchone()[0]
  148. return rid
  149. def _update_tag_lookup(self, nodeid, tid):
  150. sql_lookup = "INSERT INTO LOOKUP(nodeid, tagid) VALUES(%s, %s)"
  151. self._cur.execute(sql_lookup, (nodeid, tid))
  152. self._con.commit()
  153. def _setnodetags(self, nodeid, tags):
  154. for tag in tags:
  155. tid = self._get_or_create_tag(tag)
  156. self._update_tag_lookup(nodeid, tid)
  157. def _get_node_tags(self, node):
  158. sql = "SELECT tagid FROM LOOKUP WHERE NODEID = %s"
  159. self._cur.execute(sql, (str(node[0]),))
  160. tagids = self._cur.fetchall()
  161. if tagids:
  162. sql = ("SELECT DATA FROM TAG WHERE ID IN (%s)"
  163. "" % ','.join(['%s']*len(tagids)))
  164. tagids = [str(id[0]) for id in tagids]
  165. self._cur.execute(sql, (tagids))
  166. tags = self._cur.fetchall()
  167. for t in tags:
  168. yield t[0]
  169. def getnodes(self, ids):
  170. if ids:
  171. sql = ("SELECT * FROM NODE WHERE ID IN ({})"
  172. "".format(','.join('%s' for i in ids)))
  173. else:
  174. sql = "SELECT * FROM NODE"
  175. self._cur.execute(sql, (ids))
  176. nodes = self._cur.fetchall()
  177. nodes_w_tags = []
  178. for node in nodes:
  179. tags = list(self._get_node_tags(node))
  180. nodes_w_tags.append(list(node) + tags)
  181. return nodes_w_tags
  182. def editnode(self, nid, **kwargs): # pragma: no cover
  183. tags = kwargs.pop('tags', None)
  184. sql = ("UPDATE NODE SET %s WHERE ID = %%s "
  185. "" % ','.join('%s=%%s' % k for k in list(kwargs)))
  186. self._cur.execute(sql, (list(kwargs.values()) + [nid]))
  187. if tags:
  188. # update all old node entries in lookup
  189. # create new entries
  190. # clean all old tags
  191. sql_clean = "DELETE FROM LOOKUP WHERE NODEID=?"
  192. self._cur.execute(sql_clean, (str(nid),))
  193. self._setnodetags(nid, tags)
  194. self._con.commit()
  195. def removenodes(self, nid):
  196. # shall we do this also in the sqlite driver?
  197. sql_clean = "DELETE FROM LOOKUP WHERE NODEID=%s"
  198. self._cur.execute(sql_clean, nid)
  199. sql_rm = "delete from node where id = %s"
  200. self._cur.execute(sql_rm, nid)
  201. self._con.commit()
  202. def _clean_orphans(self):
  203. clean = ("delete from tag where not exists "
  204. "(select 'x' from lookup l where l.tagid = tag.id)")
  205. self._cur.execute(clean)
  206. self._con.commit()
  207. def savekey(self, key):
  208. salt, digest = key.split('$6$')
  209. sql = "INSERT INTO CRYPTO(SEED, DIGEST) VALUES(%s,%s)"
  210. self._cur.execute("DELETE FROM CRYPTO")
  211. self._cur.execute(sql, (salt, digest))
  212. self._digest = digest.encode('utf-8')
  213. self._salt = salt.encode('utf-8')
  214. self._con.commit()
  215. def loadkey(self):
  216. sql = "SELECT * FROM CRYPTO"
  217. try:
  218. self._cur.execute(sql)
  219. seed, digest = self._cur.fetchone()
  220. return seed + u'$6$' + digest
  221. except TypeError: # pragma: no cover
  222. return None
  223. def close(self): # pragma: no cover
  224. self._clean_orphans()
  225. self._cur.close()
  226. self._con.close()