postgresql.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 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 import parse as 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'):
  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 close(self):
  66. # TODO: implement _clean_orphands
  67. self._cur.close()
  68. self._con.close()
  69. def listtags(self, filter=None):
  70. pass
  71. def editnode(self, nid, **kwargs):
  72. pass
  73. def add_node(self, node):
  74. sql = ("INSERT INTO NODE(USERNAME, PASSWORD, URL, NOTES)"
  75. "VALUES(%s, %s, %s, %s)")
  76. node_tags = list(node)
  77. node, tags = node_tags[:4], node_tags[-1]
  78. self._cur.execute(sql, (node))
  79. #self._setnodetags(self._cur.lastrowid, tags)
  80. self._con.commit()
  81. def getnodes(self, ids):
  82. sql = "SELECT * FROM NODE WHERE ID IN ({})".format(','.join('%s' for
  83. i in ids))
  84. self._cur.execute(sql, (ids))
  85. nodes = self._cur.fetchall()
  86. nodes_w_tags = []
  87. for node in nodes:
  88. #tags = list(self._get_node_tags(node))
  89. tags = []
  90. nodes_w_tags.append(list(node) + tags)
  91. return nodes_w_tags
  92. def removenodes(self, nodes):
  93. pass
  94. def listnodes(self):
  95. pass
  96. def _create_tables(self):
  97. try:
  98. self._cur.execute("SELECT 1 from DBVERSION")
  99. version = self._cur.fetchone()
  100. if version:
  101. return
  102. except pg.ProgrammingError:
  103. self._con.rollback()
  104. try:
  105. self._cur.execute("CREATE TABLE NODE(ID SERIAL PRIMARY KEY, "
  106. "USERNAME TEXT NOT NULL, "
  107. "PASSWORD TEXT NOT NULL, "
  108. "URL TEXT NOT NULL, "
  109. "NOTES TEXT NOT NULL"
  110. ")")
  111. self._cur.execute("CREATE TABLE TAG"
  112. "(ID SERIAL PRIMARY KEY,"
  113. "DATA TEXT NOT NULL UNIQUE)")
  114. self._cur.execute("CREATE TABLE LOOKUP ("
  115. "nodeid SERIAL REFERENCES NODE(ID),"
  116. "tagid SERIAL REFERENCES TAG(ID)"
  117. ")")
  118. self._cur.execute("CREATE TABLE CRYPTO "
  119. "(SEED TEXT, DIGEST TEXT)")
  120. self._cur.execute("CREATE TABLE DBVERSION("
  121. "VERSION TEXT NOT NULL DEFAULT {}"
  122. ")".format(__DB_FORMAT__))
  123. self._cur.execute("INSERT INTO DBVERSION VALUES(%s)",
  124. (self.dbversion,))
  125. self._con.commit()
  126. except pg.ProgrammingError:
  127. self._con.rollback()
  128. def save_crypto_info(self, seed, digest):
  129. """save the random seed and the digested key"""
  130. self._cur.execute("DELETE FROM CRYPTO")
  131. self._cur.execute("INSERT INTO CRYPTO VALUES(%s, %s)", (seed, digest))
  132. self._con.commit()
  133. def fetch_crypto_info(self):
  134. self._cur.execute("SELECT * FROM CRYPTO")
  135. row = self._cur.fetchone()
  136. return row
  137. def savekey(self, key):
  138. salt, digest = key.split('$6$')
  139. sql = "INSERT INTO CRYPTO(SEED, DIGEST) VALUES(%s,%s)"
  140. self._cur.execute("DELETE FROM CRYPTO")
  141. self._cur.execute(sql, (salt, digest))
  142. self._digest = digest.encode('utf-8')
  143. self._salt = salt.encode('utf-8')
  144. self._con.commit()
  145. def loadkey(self):
  146. sql = "SELECT * FROM CRYPTO"
  147. try:
  148. self._cur.execute(sql)
  149. seed, digest = self._cur.fetchone()
  150. return seed + u'$6$' + digest
  151. except TypeError:
  152. return None