MultiuserPlugin.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import re
  2. import sys
  3. import json
  4. from Config import config
  5. from Plugin import PluginManager
  6. from Crypt import CryptBitcoin
  7. from . import UserPlugin
  8. from util.Flag import flag
  9. from Translate import translate as _
  10. # We can only import plugin host clases after the plugins are loaded
  11. @PluginManager.afterLoad
  12. def importPluginnedClasses():
  13. global UserManager
  14. from User import UserManager
  15. try:
  16. local_master_addresses = set(json.load(open("%s/users.json" % config.data_dir)).keys()) # Users in users.json
  17. except Exception as err:
  18. local_master_addresses = set()
  19. @PluginManager.registerTo("UiRequest")
  20. class UiRequestPlugin(object):
  21. def __init__(self, *args, **kwargs):
  22. self.user_manager = UserManager.user_manager
  23. super(UiRequestPlugin, self).__init__(*args, **kwargs)
  24. # Create new user and inject user welcome message if necessary
  25. # Return: Html body also containing the injection
  26. def actionWrapper(self, path, extra_headers=None):
  27. match = re.match("/(?P<address>[A-Za-z0-9\._-]+)(?P<inner_path>/.*|$)", path)
  28. if not match:
  29. return False
  30. inner_path = match.group("inner_path").lstrip("/")
  31. html_request = "." not in inner_path or inner_path.endswith(".html") # Only inject html to html requests
  32. user_created = False
  33. if html_request:
  34. user = self.getCurrentUser() # Get user from cookie
  35. if not user: # No user found by cookie
  36. user = self.user_manager.create()
  37. user_created = True
  38. else:
  39. user = None
  40. # Disable new site creation if --multiuser_no_new_sites enabled
  41. if config.multiuser_no_new_sites:
  42. path_parts = self.parsePath(path)
  43. if not self.server.site_manager.get(match.group("address")) and (not user or user.master_address not in local_master_addresses):
  44. self.sendHeader(404)
  45. return self.formatError("Not Found", "Adding new sites disabled on this proxy", details=False)
  46. if user_created:
  47. if not extra_headers:
  48. extra_headers = {}
  49. extra_headers['Set-Cookie'] = "master_address=%s;path=/;max-age=2592000;" % user.master_address # = 30 days
  50. loggedin = self.get.get("login") == "done"
  51. back_generator = super(UiRequestPlugin, self).actionWrapper(path, extra_headers) # Get the wrapper frame output
  52. if not back_generator: # Wrapper error or not string returned, injection not possible
  53. return False
  54. elif loggedin:
  55. back = next(back_generator)
  56. inject_html = """
  57. <!-- Multiser plugin -->
  58. <script nonce="{script_nonce}">
  59. setTimeout(function() {
  60. zeroframe.cmd("wrapperNotification", ["done", "{message}<br><small>You have been logged in successfully</small>", 5000])
  61. }, 1000)
  62. </script>
  63. </body>
  64. </html>
  65. """.replace("\t", "")
  66. if user.master_address in local_master_addresses:
  67. message = "Hello master!"
  68. else:
  69. message = "Hello again!"
  70. inject_html = inject_html.replace("{message}", message)
  71. inject_html = inject_html.replace("{script_nonce}", self.getScriptNonce())
  72. return iter([re.sub(b"</body>\s*</html>\s*$", inject_html.encode(), back)]) # Replace the </body></html> tags with the injection
  73. else: # No injection necessary
  74. return back_generator
  75. # Get the current user based on request's cookies
  76. # Return: User object or None if no match
  77. def getCurrentUser(self):
  78. cookies = self.getCookies()
  79. user = None
  80. if "master_address" in cookies:
  81. users = self.user_manager.list()
  82. user = users.get(cookies["master_address"])
  83. return user
  84. @PluginManager.registerTo("UiWebsocket")
  85. class UiWebsocketPlugin(object):
  86. def __init__(self, *args, **kwargs):
  87. if config.multiuser_no_new_sites:
  88. flag.no_multiuser(self.actionMergerSiteAdd)
  89. super(UiWebsocketPlugin, self).__init__(*args, **kwargs)
  90. # Let the page know we running in multiuser mode
  91. def formatServerInfo(self):
  92. server_info = super(UiWebsocketPlugin, self).formatServerInfo()
  93. server_info["multiuser"] = True
  94. if "ADMIN" in self.site.settings["permissions"]:
  95. server_info["master_address"] = self.user.master_address
  96. is_multiuser_admin = config.multiuser_local or self.user.master_address in local_master_addresses
  97. server_info["multiuser_admin"] = is_multiuser_admin
  98. return server_info
  99. # Show current user's master seed
  100. @flag.admin
  101. def actionUserShowMasterSeed(self, to):
  102. message = "<b style='padding-top: 5px; display: inline-block'>Your unique private key:</b>"
  103. message += "<div style='font-size: 84%%; background-color: #FFF0AD; padding: 5px 8px; margin: 9px 0px'>%s</div>" % self.user.master_seed
  104. message += "<small>(Save it, you can access your account using this information)</small>"
  105. self.cmd("notification", ["info", message])
  106. # Logout user
  107. @flag.admin
  108. def actionUserLogout(self, to):
  109. message = "<b>You have been logged out.</b> <a href='#Login' class='button' id='button_notification'>Login to another account</a>"
  110. self.cmd("notification", ["done", message, 1000000]) # 1000000 = Show ~forever :)
  111. script = "document.cookie = 'master_address=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';"
  112. script += "$('#button_notification').on('click', function() { zeroframe.cmd(\"userLoginForm\", []); });"
  113. self.cmd("injectScript", script)
  114. # Delete from user_manager
  115. user_manager = UserManager.user_manager
  116. if self.user.master_address in user_manager.users:
  117. if not config.multiuser_local:
  118. del user_manager.users[self.user.master_address]
  119. self.response(to, "Successful logout")
  120. else:
  121. self.response(to, "User not found")
  122. @flag.admin
  123. def actionUserSet(self, to, master_address):
  124. user_manager = UserManager.user_manager
  125. user = user_manager.get(master_address)
  126. if not user:
  127. raise Exception("No user found")
  128. script = "document.cookie = 'master_address=%s;path=/;max-age=2592000;';" % master_address
  129. script += "zeroframe.cmd('wrapperReload', ['login=done']);"
  130. self.cmd("notification", ["done", "Successful login, reloading page..."])
  131. self.cmd("injectScript", script)
  132. self.response(to, "ok")
  133. @flag.admin
  134. def actionUserSelectForm(self, to):
  135. if not config.multiuser_local:
  136. raise Exception("Only allowed in multiuser local mode")
  137. user_manager = UserManager.user_manager
  138. body = "<span style='padding-bottom: 5px; display: inline-block'>" + "Change account:" + "</span>"
  139. for master_address, user in user_manager.list().items():
  140. is_active = self.user.master_address == master_address
  141. if user.certs:
  142. first_cert = next(iter(user.certs.keys()))
  143. title = "%s@%s" % (user.certs[first_cert]["auth_user_name"], first_cert)
  144. else:
  145. title = user.master_address
  146. if len(user.sites) < 2 and not is_active: # Avoid listing ad-hoc created users
  147. continue
  148. if is_active:
  149. css_class = "active"
  150. else:
  151. css_class = "noclass"
  152. body += "<a href='#Select+user' class='select select-close user %s' title='%s'>%s</a>" % (css_class, user.master_address, title)
  153. script = """
  154. $(".notification .select.user").on("click", function() {
  155. $(".notification .select").removeClass('active')
  156. zeroframe.response(%s, this.title)
  157. return false
  158. })
  159. """ % self.next_message_id
  160. self.cmd("notification", ["ask", body], lambda master_address: self.actionUserSet(to, master_address))
  161. self.cmd("injectScript", script)
  162. # Show login form
  163. def actionUserLoginForm(self, to):
  164. self.cmd("prompt", ["<b>Login</b><br>Your private key:", "password", "Login"], self.responseUserLogin)
  165. # Login form submit
  166. def responseUserLogin(self, master_seed):
  167. user_manager = UserManager.user_manager
  168. user = user_manager.get(CryptBitcoin.privatekeyToAddress(master_seed))
  169. if not user:
  170. user = user_manager.create(master_seed=master_seed)
  171. if user.master_address:
  172. script = "document.cookie = 'master_address=%s;path=/;max-age=2592000;';" % user.master_address
  173. script += "zeroframe.cmd('wrapperReload', ['login=done']);"
  174. self.cmd("notification", ["done", "Successful login, reloading page..."])
  175. self.cmd("injectScript", script)
  176. else:
  177. self.cmd("notification", ["error", "Error: Invalid master seed"])
  178. self.actionUserLoginForm(0)
  179. def hasCmdPermission(self, cmd):
  180. flags = flag.db.get(self.getCmdFuncName(cmd), ())
  181. is_public_proxy_user = not config.multiuser_local and self.user.master_address not in local_master_addresses
  182. if is_public_proxy_user and "no_multiuser" in flags:
  183. self.cmd("notification", ["info", _("This function ({cmd}) is disabled on this proxy!")])
  184. return False
  185. else:
  186. return super(UiWebsocketPlugin, self).hasCmdPermission(cmd)
  187. def actionCertAdd(self, *args, **kwargs):
  188. super(UiWebsocketPlugin, self).actionCertAdd(*args, **kwargs)
  189. master_seed = self.user.master_seed
  190. message = """
  191. <style>
  192. .masterseed {
  193. font-size: 85%; background-color: #FFF0AD; padding: 5px 8px; margin: 9px 0px; width: 100%;
  194. box-sizing: border-box; border: 0px; text-align: center; cursor: pointer;
  195. }
  196. </style>
  197. <b>Hello, welcome to ZeroProxy!</b><div style='margin-top: 8px'>A new, unique account created for you:</div>
  198. <input type='text' class='masterseed' id='button_notification_masterseed' value='Click here to show' readonly/>
  199. <div style='text-align: center; font-size: 85%; margin-bottom: 10px;'>
  200. or <a href='#Download' id='button_notification_download'
  201. class='masterseed_download' download='zeronet_private_key.backup'>Download backup as text file</a>
  202. </div>
  203. <div>
  204. This is your private key, <b>save it</b>, so you can login next time.<br>
  205. <b>Warning: Without this key, your account will be lost forever!</b>
  206. </div><br>
  207. <a href='#' class='button' style='margin-left: 0px'>Ok, Saved it!</a><br><br>
  208. <small>This site allows you to browse ZeroNet content, but if you want to secure your account <br>
  209. and help to keep the network alive, then please run your own <a href='https://zeronet.io' target='_blank'>ZeroNet client</a>.</small>
  210. """
  211. self.cmd("notification", ["info", message])
  212. script = """
  213. $("#button_notification_masterseed").on("click", function() {
  214. this.value = "{master_seed}"; this.setSelectionRange(0,100);
  215. })
  216. $("#button_notification_download").on("mousedown", function() {
  217. this.href = window.URL.createObjectURL(new Blob(["ZeroNet user master seed:\\r\\n{master_seed}"]))
  218. })
  219. """.replace("{master_seed}", master_seed)
  220. self.cmd("injectScript", script)
  221. def actionPermissionAdd(self, to, permission):
  222. is_public_proxy_user = not config.multiuser_local and self.user.master_address not in local_master_addresses
  223. if permission == "NOSANDBOX" and is_public_proxy_user:
  224. self.cmd("notification", ["info", "You can't disable sandbox on this proxy!"])
  225. self.response(to, {"error": "Denied by proxy"})
  226. return False
  227. else:
  228. return super(UiWebsocketPlugin, self).actionPermissionAdd(to, permission)
  229. @PluginManager.registerTo("ConfigPlugin")
  230. class ConfigPlugin(object):
  231. def createArguments(self):
  232. group = self.parser.add_argument_group("Multiuser plugin")
  233. group.add_argument('--multiuser_local', help="Enable unsafe Ui functions and write users to disk", action='store_true')
  234. group.add_argument('--multiuser_no_new_sites', help="Denies adding new sites by normal users", action='store_true')
  235. return super(ConfigPlugin, self).createArguments()