webui.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. tmplt = """
  37. %#template to generate a HTML table from a list of tuples (or list of lists, or tuple of tuples or ...)
  38. <form action="/" method="POST">
  39. <select multiple name="tag" onchange="this.form.submit()">
  40. %for tag in tags:
  41. <option value="{{tag}}">{{tag}}</option>
  42. %end
  43. </select>
  44. </form>
  45. <p>Click on username to view the details:</p>
  46. <table border="1">
  47. %for node in nodes:
  48. <tr>
  49. %#for item in node:
  50. %# <td><a href={{node._id}}><{{item}}</a></td>
  51. <td><a href=/node/{{node._id}}>{{node.username}}@{{node.url}}</a></td>
  52. <td>{{ ', '.join([t.strip() for t in filter(None, node.tags)]) }}</td>
  53. <tr><td></td><td>edit</td></tr>
  54. %end
  55. </tr>
  56. %end
  57. </table>
  58. """
  59. login = """
  60. <p>Please enter your database password: <b>
  61. <form action="/auth" method="POST">
  62. Password: <input type="password" name="pwd">
  63. </form>"""
  64. def get_conf(args):
  65. config_dir = os.path.expanduser("~/.pwman")
  66. if not os.path.isdir(config_dir):
  67. os.mkdir(config_dir)
  68. if not os.path.exists(args.cfile):
  69. config.set_defaults(default_config)
  70. else:
  71. config.load(args.cfile)
  72. return config
  73. def set_xsel(config, OSX):
  74. if not OSX:
  75. xselpath = which("xsel")
  76. config.set_value("Global", "xsel", xselpath)
  77. elif OSX:
  78. pbcopypath = which("pbcopy")
  79. config.set_value("Global", "xsel", pbcopypath)
  80. def set_win_colors(config):
  81. if 'win' in sys.platform:
  82. try:
  83. import colorama
  84. colorama.init()
  85. except ImportError:
  86. config.set_value("Global", "colors", 'no')
  87. def set_umask(config):
  88. # set umask before creating/opening any files
  89. try:
  90. umask = config.get_value("Global", "umask")
  91. if re.search(r'^\d{4}$', umask):
  92. os.umask(int(umask))
  93. else:
  94. raise ValueError
  95. except ValueError:
  96. print("Could not determine umask from config!")
  97. sys.exit(2)
  98. def set_db(args):
  99. if args.dbase:
  100. config.set_value("Database", "filename", args.dbase)
  101. config.set_value("Global", "save", "False")
  102. def set_algorithm(args, config):
  103. if args.algo:
  104. config.set_value("Encryption", "algorithm", args.algo)
  105. config.set_value("Global", "save", "False")
  106. def get_conf_options(args, OSX):
  107. config = get_conf(args)
  108. xselpath = config.get_value("Global", "xsel")
  109. if not xselpath:
  110. set_xsel(config, OSX)
  111. set_win_colors(config)
  112. set_db(args)
  113. set_umask(config)
  114. set_algorithm(args, config)
  115. dbtype = config.get_value("Database", "type")
  116. if not dbtype:
  117. print("Could not read the Database type from the config!")
  118. sys.exit(1)
  119. return xselpath, dbtype
  120. @route('/node/:no')
  121. @validate(no=int)
  122. def view_node(no):
  123. pass
  124. @route('/edit/:no', method='GET')
  125. @validate(no=int)
  126. def edit_node(no):
  127. pass
  128. @route('/auth', method=['GET', 'POST'])
  129. def is_authenticated():
  130. global AUTHENTICATED
  131. crypto = CryptoEngine.get()
  132. if request.method == 'POST':
  133. key = request.POST.get('pwd', '')
  134. crypto.auth(key)
  135. AUTHENTICATED = True
  136. redirect('/')
  137. else:
  138. return login
  139. @route('/', method=['GET', 'POST'])
  140. def listnodes():
  141. global AUTHENTICATED, TAGS
  142. _filter = None
  143. OSX = False
  144. args = parser_options().parse_args()
  145. xselpath, dbtype = get_conf_options(args, OSX)
  146. dbver = 0.4
  147. db = pwman.data.factory.create(dbtype, dbver)
  148. db.open()
  149. crypto = CryptoEngine.get()
  150. if not AUTHENTICATED:
  151. redirect('/auth')
  152. if 'POST' in request.method:
  153. _filter = request.POST.get('tag')
  154. if _filter:
  155. db._filtertags = [TagNew(_filter.strip())]
  156. if _filter == 'None':
  157. db._filtertags = []
  158. nodeids = db.listnodes()
  159. nodes = db.getnodes(nodeids)
  160. nodesd = [''] * len(nodes)
  161. for idx, node in enumerate(nodes):
  162. ntags = [t.strip() for t in filter(None, node.tags)]
  163. print(node._id)
  164. nodesd[idx] = ('@'.join((node.username, node.url)),
  165. ', '.join(ntags))
  166. if not TAGS:
  167. TAGS = list(set([''.join(node.tags).strip() for node in nodes]))
  168. TAGS.sort()
  169. TAGS.insert(0, 'None')
  170. print(len(TAGS))
  171. output = template(tmplt, nodes=nodes, tags=TAGS)
  172. return output
  173. debug(True)
  174. run(reloader=True)