mysql.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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) 2012-2015 Oz Nahum <nahumoz@gmail.com>
  18. # ============================================================================
  19. #mysql -u root -p
  20. #create database pwmantest
  21. #create user 'pwman'@'localhost' IDENTIFIED BY '123456';
  22. #grant all on pwmantest.* to 'pwman'@'localhost';
  23. """MySQL Database implementation."""
  24. from __future__ import print_function
  25. from pwman.data.database import Database, __DB_FORMAT__
  26. import MySQLdb as mysql
  27. class MySQLDatabase(Database):
  28. @classmethod
  29. def check_db_version(cls, dburi):
  30. port = 3306
  31. credentials, host = dburi.netloc.split('@')
  32. user, passwd = credentials.split(':')
  33. if ':' in host:
  34. host, port = host.split(':')
  35. port = int(port)
  36. con = mysql.connect(host=host, port=port, user=user, passwd=passwd,
  37. db=dburi.path.lstrip('/'))
  38. cur = con.cursor()
  39. try:
  40. cur.execute("SELECT VERSION FROM DBVERSION")
  41. version = cur.fetchone()
  42. cur.close()
  43. con.close()
  44. return version[-1]
  45. except mysql.ProgrammingError:
  46. con.rollback()
  47. def __init__(self, mysqluri, dbformat=__DB_FORMAT__):
  48. self.dburi = mysqluri
  49. self.dbversion = dbformat
  50. def _open(self):
  51. port = 3306
  52. credentials, host = self.dburi.netloc.split('@')
  53. user, passwd = credentials.split(':')
  54. if ':' in host:
  55. host, port = host.split(':')
  56. port = int(port)
  57. self._con = mysql.connect(host=host, port=port, user=user,
  58. passwd=passwd,
  59. db=self.dburi.path.lstrip('/'))
  60. self._cur = self._con.cursor()
  61. self._create_tables()
  62. def _create_tables(self):
  63. try:
  64. self._cur.execute("SELECT 1 from DBVERSION")
  65. version = self._cur.fetchone()
  66. if version:
  67. return
  68. except mysql.ProgrammingError:
  69. self._con.rollback()
  70. try:
  71. self._cur.execute("CREATE TABLE NODE(ID SERIAL PRIMARY KEY, "
  72. "USERNAME TEXT NOT NULL, "
  73. "PASSWORD TEXT NOT NULL, "
  74. "URL TEXT NOT NULL, "
  75. "NOTES TEXT NOT NULL"
  76. ")")
  77. self._cur.execute("CREATE TABLE TAG"
  78. "(ID SERIAL PRIMARY KEY,"
  79. "DATA VARCHAR(255) NOT NULL UNIQUE)")
  80. self._cur.execute("CREATE TABLE LOOKUP ("
  81. "nodeid INTEGER NOT NULL REFERENCES NODE(ID),"
  82. "tagid INTEGER NOT NULL REFERENCES TAG(ID)"
  83. ")")
  84. self._cur.execute("CREATE TABLE CRYPTO "
  85. "(SEED TEXT, DIGEST TEXT)")
  86. self._cur.execute("CREATE TABLE DBVERSION("
  87. "VERSION TEXT NOT NULL "
  88. ")")
  89. self._cur.execute("INSERT INTO DBVERSION VALUES(%s)",
  90. (self.dbversion,))
  91. self._con.commit()
  92. except mysql.ProgrammingError: # pragma: no cover
  93. self._con.rollback()
  94. def getnodes(self, ids):
  95. if ids:
  96. sql = ("SELECT * FROM NODE WHERE ID IN ({})"
  97. "".format(','.join('%s' for i in ids)))
  98. else:
  99. sql = "SELECT * FROM NODE"
  100. self._cur.execute(sql, (ids))
  101. nodes = self._cur.fetchall()
  102. nodes_w_tags = []
  103. for node in nodes:
  104. tags = list(self._get_node_tags(node))
  105. nodes_w_tags.append(list(node) + tags)
  106. return nodes_w_tags
  107. def add_node(self, node):
  108. sql = ("INSERT INTO NODE(USERNAME, PASSWORD, URL, NOTES)"
  109. "VALUES(%s, %s, %s, %s)")
  110. node_tags = list(node)
  111. node, tags = node_tags[:4], node_tags[-1]
  112. self._cur.execute(sql, (node))
  113. nid = self._cur.lastrowid
  114. self._setnodetags(nid, tags)
  115. self._con.commit()
  116. def _get_node_tags(self, node):
  117. sql = "SELECT tagid FROM LOOKUP WHERE NODEID = %s"
  118. self._cur.execute(sql, (str(node[0]),))
  119. tagids = self._cur.fetchall()
  120. if tagids:
  121. sql = ("SELECT DATA FROM TAG WHERE ID IN (%s)"
  122. "" % ','.join(['%s']*len(tagids)))
  123. tagids = [str(id[0]) for id in tagids]
  124. self._cur.execute(sql, (tagids))
  125. tags = self._cur.fetchall()
  126. for t in tags:
  127. yield t[0]
  128. def _setnodetags(self, nodeid, tags):
  129. for tag in tags:
  130. tid = self._get_or_create_tag(tag)
  131. self._update_tag_lookup(nodeid, tid)
  132. def _get_tag(self, tagcipher):
  133. sql_search = "SELECT ID FROM TAG WHERE DATA = %s"
  134. self._cur.execute(sql_search, ([tagcipher]))
  135. rv = self._cur.fetchone()
  136. return rv
  137. def _get_or_create_tag(self, tagcipher):
  138. rv = self._get_tag(tagcipher)
  139. if rv:
  140. return rv[0]
  141. else:
  142. sql_insert = "INSERT INTO TAG(DATA) VALUES(%s)"
  143. self._cur.execute(sql_insert, ([tagcipher]))
  144. return self._cur.lastrowid
  145. def _update_tag_lookup(self, nodeid, tid):
  146. sql_lookup = "INSERT INTO LOOKUP(nodeid, tagid) VALUES(%s, %s)"
  147. self._cur.execute(sql_lookup, (nodeid, tid))
  148. self._con.commit()
  149. def fetch_crypto_info(self):
  150. self._cur.execute("SELECT * FROM CRYPTO")
  151. row = self._cur.fetchone()
  152. return row
  153. def listtags(self):
  154. self._clean_orphans()
  155. get_tags = "select DATA from TAG"
  156. self._cur.execute(get_tags)
  157. tags = self._cur.fetchall()
  158. if tags:
  159. return [t[0] for t in tags]
  160. return [] # pragma: no cover
  161. def listnodes(self, filter=None):
  162. if not filter:
  163. sql_all = "SELECT ID FROM NODE"
  164. self._cur.execute(sql_all)
  165. ids = self._cur.fetchall()
  166. return [id[0] for id in ids]
  167. else:
  168. tagid = self._get_tag(filter)
  169. if not tagid:
  170. return [] # pragma: no cover
  171. sql_filter = "SELECT NODEID FROM LOOKUP WHERE TAGID = %s "
  172. self._cur.execute(sql_filter, (tagid))
  173. self._con.commit()
  174. ids = self._cur.fetchall()
  175. return [id[0] for id in ids]
  176. def save_crypto_info(self, seed, digest):
  177. """save the random seed and the digested key"""
  178. self._cur.execute("DELETE FROM CRYPTO")
  179. self._cur.execute("INSERT INTO CRYPTO VALUES(%s, %s)", (seed, digest))
  180. self._con.commit()
  181. def loadkey(self):
  182. sql = "SELECT * FROM CRYPTO"
  183. try:
  184. self._cur.execute(sql)
  185. seed, digest = self._cur.fetchone()
  186. return seed + u'$6$' + digest
  187. except TypeError: # pragma: no cover
  188. return None
  189. def _clean_orphans(self):
  190. clean = ("delete from TAG where not exists "
  191. "(select 'x' from LOOKUP l where l.TAGID = TAG.ID)")
  192. self._cur.execute(clean)
  193. def removenodes(self, nid):
  194. # shall we do this also in the sqlite driver?
  195. sql_clean = "DELETE FROM LOOKUP WHERE NODEID=%s"
  196. self._cur.execute(sql_clean, nid)
  197. sql_rm = "delete from NODE where ID = %s"
  198. self._cur.execute(sql_rm, nid)
  199. self._con.commit()
  200. self._con.commit()
  201. def savekey(self, key):
  202. salt, digest = key.split('$6$')
  203. sql = "INSERT INTO CRYPTO(SEED, DIGEST) VALUES(%s,%s)"
  204. self._cur.execute("DELETE FROM CRYPTO")
  205. self._cur.execute(sql, (salt, digest))
  206. self._digest = digest.encode('utf-8')
  207. self._salt = salt.encode('utf-8')
  208. self._con.commit()