webui.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. #!/usr/bin/env python
  2. #============================================================================
  3. # This file is part of Pwman3.
  4. #
  5. # Pwman3 is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License, version 2
  7. # as published by the Free Software Foundation;
  8. #
  9. # Pwman3 is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Pwman3; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. #============================================================================
  18. # Copyright (C) 2012-2014 Oz Nahum <nahumoz@gmail.com>
  19. #============================================================================
  20. from __future__ import print_function
  21. from bottle import route, run, debug, template, request, get, redirect
  22. import os
  23. import sys
  24. import re
  25. import shutil
  26. from pwman import default_config, which
  27. from pwman import parser_options
  28. from pwman.ui import get_ui_platform
  29. from pwman.ui.tools import CLICallback
  30. from pwman.util.crypto import CryptoEngine
  31. import pwman.util.config as config
  32. import pwman.data.factory
  33. from pwman.data.tags import TagNew
  34. AUTHENTICATED = False
  35. TAGS = None
  36. DB = None
  37. tmplt = """
  38. %#template to generate a HTML table from a list of tuples (or list of lists, or tuple of tuples or ...)
  39. <form action="/" method="POST">
  40. <select multiple name="tag" onchange="this.form.submit()">
  41. %for tag in tags:
  42. <option value="{{tag}}">{{tag}}</option>
  43. %end
  44. </select>
  45. </form>
  46. <p>Click on username to view the details:</p>
  47. <table border="1">
  48. %for node in nodes:
  49. <tr>
  50. %#for item in node:
  51. %# <td><a href={{node._id}}><{{item}}</a></td>
  52. <td><a href=/node/{{node._id}}>{{node.username}}@{{node.url}}</a></td>
  53. <td>{{ ', '.join([t.strip() for t in filter(None, node.tags)]) }}</td>
  54. <tr><td></td><td>edit</td></tr>
  55. %end
  56. </tr>
  57. %end
  58. </table>
  59. """
  60. login = """
  61. <p>Please enter your database password: <b>
  62. <form action="/auth" method="POST">
  63. Password: <input type="password" name="pwd">
  64. </form>"""
  65. def get_conf(args):
  66. config_dir = os.path.expanduser("~/.pwman")
  67. if not os.path.isdir(config_dir):
  68. os.mkdir(config_dir)
  69. if not os.path.exists(args.cfile):
  70. config.set_defaults(default_config)
  71. else:
  72. config.load(args.cfile)
  73. return config
  74. def set_xsel(config, OSX):
  75. if not OSX:
  76. xselpath = which("xsel")
  77. config.set_value("Global", "xsel", xselpath)
  78. elif OSX:
  79. pbcopypath = which("pbcopy")
  80. config.set_value("Global", "xsel", pbcopypath)
  81. def set_win_colors(config):
  82. if 'win' in sys.platform:
  83. try:
  84. import colorama
  85. colorama.init()
  86. except ImportError:
  87. config.set_value("Global", "colors", 'no')
  88. def set_umask(config):
  89. # set umask before creating/opening any files
  90. try:
  91. umask = config.get_value("Global", "umask")
  92. if re.search(r'^\d{4}$', umask):
  93. os.umask(int(umask))
  94. else:
  95. raise ValueError
  96. except ValueError:
  97. print("Could not determine umask from config!")
  98. sys.exit(2)
  99. def set_db(args):
  100. if args.dbase:
  101. config.set_value("Database", "filename", args.dbase)
  102. config.set_value("Global", "save", "False")
  103. def set_algorithm(args, config):
  104. if args.algo:
  105. config.set_value("Encryption", "algorithm", args.algo)
  106. config.set_value("Global", "save", "False")
  107. def get_conf_options(args, OSX):
  108. config = get_conf(args)
  109. xselpath = config.get_value("Global", "xsel")
  110. if not xselpath:
  111. set_xsel(config, OSX)
  112. set_win_colors(config)
  113. set_db(args)
  114. set_umask(config)
  115. set_algorithm(args, config)
  116. dbtype = config.get_value("Database", "type")
  117. if not dbtype:
  118. print("Could not read the Database type from the config!")
  119. sys.exit(1)
  120. return xselpath, dbtype
  121. @route('/node/:no')
  122. def view_node(no):
  123. global DB
  124. node = DB.getnodes([no])
  125. tmplt = """
  126. <table border="1">
  127. <tr><td>Username:</td> <td>{{ node.username }}</td></tr>
  128. <tr><td>Password:</td> <td>{{ node.password }}</td></tr>
  129. <tr><td>Url:</td> <td>{{node.url}} </td></tr>
  130. <tr><td>Notes:</td> <td>{{node.notes}}</td></tr>
  131. <tr><td>Tags:</td> <td>{{node.tags}}</td></tr>
  132. </table>
  133. """
  134. output = template(tmplt, node=node[0])
  135. return output
  136. @route('/edit/:no', method='GET')
  137. def edit_node(no):
  138. pass
  139. @route('/auth', method=['GET', 'POST'])
  140. def is_authenticated():
  141. global AUTHENTICATED
  142. crypto = CryptoEngine.get()
  143. if request.method == 'POST':
  144. key = request.POST.get('pwd', '')
  145. crypto.auth(key)
  146. AUTHENTICATED = True
  147. redirect('/')
  148. else:
  149. return login
  150. @route('/', method=['GET', 'POST'])
  151. def listnodes():
  152. global AUTHENTICATED, TAGS, DB
  153. _filter = None
  154. OSX = False
  155. args = parser_options().parse_args()
  156. xselpath, dbtype = get_conf_options(args, OSX)
  157. dbver = 0.4
  158. DB = pwman.data.factory.create(dbtype, dbver)
  159. DB.open()
  160. crypto = CryptoEngine.get()
  161. if not AUTHENTICATED:
  162. redirect('/auth')
  163. if 'POST' in request.method:
  164. _filter = request.POST.get('tag')
  165. if _filter:
  166. DB._filtertags = [TagNew(_filter.strip())]
  167. if _filter == 'None':
  168. DB._filtertags = []
  169. nodeids = DB.listnodes()
  170. nodes = DB.getnodes(nodeids)
  171. nodesd = [''] * len(nodes)
  172. for idx, node in enumerate(nodes):
  173. ntags = [t.strip() for t in filter(None, node.tags)]
  174. nodesd[idx] = ('@'.join((node.username, node.url)),
  175. ', '.join(ntags))
  176. if not TAGS:
  177. TAGS = list(set([''.join(node.tags).strip() for node in nodes]))
  178. TAGS.sort()
  179. TAGS.insert(0, 'None')
  180. print(len(TAGS))
  181. output = template(tmplt, nodes=nodes, tags=TAGS)
  182. return output
  183. debug(True)
  184. run(reloader=True)