webui.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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, redirect, static_file
  22. from pwman.util.crypto import CryptoEngine
  23. import pwman.data.factory
  24. from pwman.data.tags import TagNew
  25. from pwman import parser_options, get_conf_options
  26. from pkg_resources import resource_filename
  27. import itertools
  28. import sys
  29. from signal import SIGTERM
  30. import os
  31. templates_path = [resource_filename('pwman', 'ui/templates')]
  32. statics = [resource_filename('pwman', 'ui/templates/static')][0]
  33. AUTHENTICATED = False
  34. TAGS = None
  35. DB = None
  36. # BUG: Error: SQLite: Incorrect number of bindings supplied.
  37. # The current statement uses 2, and there are 1 supplied.
  38. # When issuing multiple times filter
  39. # WEB GUI shows multiple tags as one tag!
  40. @route('/exit', method=['GET'])
  41. def exit():
  42. os.kill(os.getpid(), SIGTERM)
  43. def require_auth(fn):
  44. def check_auth(**kwargs):
  45. if AUTHENTICATED:
  46. return fn(**kwargs)
  47. else:
  48. redirect("/auth")
  49. return check_auth
  50. @route('/node/:no')
  51. @require_auth
  52. def view_node(no):
  53. global DB
  54. node = DB.getnodes([no])
  55. output = template("view.tpl", node=node[0], template_lookup=templates_path)
  56. return output
  57. def submit_node(id, request):
  58. # create new\update node based on request.params.items()
  59. redirect('/')
  60. @route('/new/', method=['GET', 'POST'])
  61. @route('/edit/:no', method=['GET', 'POST'])
  62. @require_auth
  63. def edit_node(no=None):
  64. global DB
  65. if 'POST' in request.method:
  66. submit_node(no, request)
  67. if no:
  68. node = DB.getnodes([no])[0]
  69. else:
  70. class Node(object):
  71. def __init__(self):
  72. self._id = None
  73. self.username = ''
  74. self.password = ''
  75. self.url = ''
  76. self.notes = ''
  77. self.tags = ''
  78. node = Node()
  79. output = template('edit.tpl', node=node,
  80. template_lookup=templates_path)
  81. return output
  82. @route('/forget', method=['GET', 'POST'])
  83. def forget():
  84. global AUTHENTICATED
  85. AUTHENTICATED = False
  86. enc = CryptoEngine.get()
  87. enc.forget()
  88. redirect('/auth')
  89. @route('/auth', method=['GET', 'POST'])
  90. def is_authenticated():
  91. global AUTHENTICATED
  92. crypto = CryptoEngine.get(dbver=0.5)
  93. if request.method == 'POST':
  94. key = request.POST.get('pwd', '')
  95. while True:
  96. try:
  97. crypto.auth(key)
  98. break
  99. except Exception:
  100. redirect('/auth')
  101. AUTHENTICATED = True
  102. redirect('/')
  103. else:
  104. return template("login.tpl", template_lookup=templates_path)
  105. @route('/', method=['GET', 'POST'])
  106. @require_auth
  107. def listnodes(apply=['require_login']):
  108. global AUTHENTICATED, TAGS, DB
  109. _filter = None
  110. if 'POST' in request.method:
  111. _filter = request.POST.get('tag')
  112. if _filter:
  113. DB._filtertags = [TagNew(_filter.strip())]
  114. if _filter == 'None':
  115. DB._filtertags = []
  116. nodeids = DB.listnodes()
  117. nodes = DB.getnodes(nodeids)
  118. nodesd = [''] * len(nodes)
  119. for idx, node in enumerate(nodes):
  120. ntags = [t.strip() for t in filter(None, node.tags)]
  121. nodesd[idx] = ('@'.join((node.username, node.url)),
  122. ', '.join(ntags))
  123. if not TAGS:
  124. t = [node.tags for node in nodes]
  125. t1 = list(itertools.chain.from_iterable(t))
  126. TAGS = list(set(t1))
  127. TAGS.sort()
  128. TAGS.insert(0, 'None')
  129. html_nodes = template("main.tpl", nodes=nodes, tags=TAGS,
  130. template_lookup=[resource_filename('pwman',
  131. 'ui/templates')])
  132. return html_nodes
  133. @route('/static/<filepath:path>')
  134. def server_static(filepath):
  135. return static_file(filepath, root=statics)
  136. class Pwman3WebDaemon(object):
  137. def __enter__(self):
  138. return self
  139. def run(self):
  140. global AUTHENTICATED, TAGS, DB
  141. OSX = False
  142. sys.argv = []
  143. args = parser_options().parse_args()
  144. xselpath, dbtype = get_conf_options(args, OSX)
  145. dbver = 0.5
  146. DB = pwman.data.factory.create(dbtype, dbver)
  147. DB.open(dbver=0.5)
  148. print(dir(DB))
  149. CryptoEngine.get(dbver=0.5)
  150. print(pwman.config._conf)
  151. debug(True)
  152. run(port=9030)
  153. def __exit__(self, type, value, traceback):
  154. return isinstance(value, TypeError)
  155. if __name__ == '__main__':
  156. with Pwman3WebDaemon() as webui:
  157. webui.run()