1
0

MultiuserPlugin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. import UserPlugin
  8. try:
  9. local_master_addresses = set(json.load(open("%s/users.json" % config.data_dir)).keys()) # Users in users.json
  10. except Exception, err:
  11. local_master_addresses = set()
  12. @PluginManager.registerTo("UiRequest")
  13. class UiRequestPlugin(object):
  14. def __init__(self, *args, **kwargs):
  15. self.user_manager = sys.modules["User.UserManager"].user_manager
  16. super(UiRequestPlugin, self).__init__(*args, **kwargs)
  17. # Create new user and inject user welcome message if necessary
  18. # Return: Html body also containing the injection
  19. def actionWrapper(self, path, extra_headers=None):
  20. match = re.match("/(?P<address>[A-Za-z0-9\._-]+)(?P<inner_path>/.*|$)", path)
  21. if not match:
  22. return False
  23. inner_path = match.group("inner_path").lstrip("/")
  24. html_request = "." not in inner_path or inner_path.endswith(".html") # Only inject html to html requests
  25. user_created = False
  26. if html_request:
  27. user = self.getCurrentUser() # Get user from cookie
  28. if not user: # No user found by cookie
  29. user = self.user_manager.create()
  30. user_created = True
  31. else:
  32. user = None
  33. # Disable new site creation if --multiuser_no_new_sites enabled
  34. if config.multiuser_no_new_sites:
  35. path_parts = self.parsePath(path)
  36. if not self.server.site_manager.get(match.group("address")) and (not user or user.master_address not in local_master_addresses):
  37. self.sendHeader(404)
  38. return self.formatError("Not Found", "Adding new sites disabled on this proxy", details=False)
  39. if user_created:
  40. if not extra_headers:
  41. extra_headers = {}
  42. extra_headers['Set-Cookie'] = "master_address=%s;path=/;max-age=2592000;" % user.master_address # = 30 days
  43. loggedin = self.get.get("login") == "done"
  44. back_generator = super(UiRequestPlugin, self).actionWrapper(path, extra_headers) # Get the wrapper frame output
  45. if not back_generator: # Wrapper error or not string returned, injection not possible
  46. return False
  47. elif loggedin:
  48. back = back_generator.next()
  49. inject_html = """
  50. <!-- Multiser plugin -->
  51. <script nonce="{script_nonce}">
  52. setTimeout(function() {
  53. zeroframe.cmd("wrapperNotification", ["done", "{message}<br><small>You have been logged in successfully</small>", 5000])
  54. }, 1000)
  55. </script>
  56. </body>
  57. </html>
  58. """.replace("\t", "")
  59. if user.master_address in local_master_addresses:
  60. message = "Hello master!"
  61. else:
  62. message = "Hello again!"
  63. inject_html = inject_html.replace("{message}", message)
  64. inject_html = inject_html.replace("{script_nonce}", self.getScriptNonce())
  65. return iter([re.sub("</body>\s*</html>\s*$", inject_html, back)]) # Replace the </body></html> tags with the injection
  66. else: # No injection necessary
  67. return back_generator
  68. # Get the current user based on request's cookies
  69. # Return: User object or None if no match
  70. def getCurrentUser(self):
  71. cookies = self.getCookies()
  72. user = None
  73. if "master_address" in cookies:
  74. users = self.user_manager.list()
  75. user = users.get(cookies["master_address"])
  76. return user
  77. @PluginManager.registerTo("UiWebsocket")
  78. class UiWebsocketPlugin(object):
  79. def __init__(self, *args, **kwargs):
  80. self.multiuser_denied_cmds = (
  81. "sitePause", "siteResume", "siteDelete", "configSet", "serverShutdown", "serverUpdate", "siteClone",
  82. "siteSetOwned", "siteSetAutodownloadoptional", "dbReload", "dbRebuild",
  83. "mergerSiteDelete", "siteSetLimit", "siteSetAutodownloadBigfileLimit",
  84. "optionalLimitSet", "optionalHelp", "optionalHelpRemove", "optionalHelpAll", "optionalFilePin", "optionalFileUnpin", "optionalFileDelete",
  85. "muteAdd", "muteRemove", "siteblockAdd", "siteblockRemove", "filterIncludeAdd", "filterIncludeRemove"
  86. )
  87. if config.multiuser_no_new_sites:
  88. self.multiuser_denied_cmds += ("mergerSiteAdd", )
  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. return server_info
  97. # Show current user's master seed
  98. def actionUserShowMasterSeed(self, to):
  99. if "ADMIN" not in self.site.settings["permissions"]:
  100. return self.response(to, "Show master seed not allowed")
  101. message = "<b style='padding-top: 5px; display: inline-block'>Your unique private key:</b>"
  102. message += "<div style='font-size: 84%%; background-color: #FFF0AD; padding: 5px 8px; margin: 9px 0px'>%s</div>" % self.user.master_seed
  103. message += "<small>(Save it, you can access your account using this information)</small>"
  104. self.cmd("notification", ["info", message])
  105. # Logout user
  106. def actionUserLogout(self, to):
  107. if "ADMIN" not in self.site.settings["permissions"]:
  108. return self.response(to, "Logout not allowed")
  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 = sys.modules["User.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. # Show login form
  123. def actionUserLoginForm(self, to):
  124. self.cmd("prompt", ["<b>Login</b><br>Your private key:", "password", "Login"], self.responseUserLogin)
  125. # Login form submit
  126. def responseUserLogin(self, master_seed):
  127. user_manager = sys.modules["User.UserManager"].user_manager
  128. user = user_manager.get(CryptBitcoin.privatekeyToAddress(master_seed))
  129. if not user:
  130. user = user_manager.create(master_seed=master_seed)
  131. if user.master_address:
  132. script = "document.cookie = 'master_address=%s;path=/;max-age=2592000;';" % user.master_address
  133. script += "zeroframe.cmd('wrapperReload', ['login=done']);"
  134. self.cmd("notification", ["done", "Successful login, reloading page..."])
  135. self.cmd("injectScript", script)
  136. else:
  137. self.cmd("notification", ["error", "Error: Invalid master seed"])
  138. self.actionUserLoginForm(0)
  139. def hasCmdPermission(self, cmd):
  140. cmd = cmd[0].lower() + cmd[1:]
  141. if not config.multiuser_local and self.user.master_address not in local_master_addresses and cmd in self.multiuser_denied_cmds:
  142. self.cmd("notification", ["info", "This function is disabled on this proxy!"])
  143. return False
  144. else:
  145. return super(UiWebsocketPlugin, self).hasCmdPermission(cmd)
  146. def actionCertAdd(self, *args, **kwargs):
  147. super(UiWebsocketPlugin, self).actionCertAdd(*args, **kwargs)
  148. master_seed = self.user.master_seed
  149. message = """
  150. <style>
  151. .masterseed {
  152. font-size: 85%; background-color: #FFF0AD; padding: 5px 8px; margin: 9px 0px; width: 100%;
  153. box-sizing: border-box; border: 0px; text-align: center; cursor: pointer;
  154. }
  155. </style>
  156. <b>Hello, welcome to ZeroProxy!</b><div style='margin-top: 8px'>A new, unique account created for you:</div>
  157. <input type='text' class='masterseed' id='button_notification_masterseed' value='Click here to show' readonly/>
  158. <div style='text-align: center; font-size: 85%; margin-bottom: 10px;'>
  159. or <a href='#Download' id='button_notification_download'
  160. class='masterseed_download' download='zeronet_private_key.backup'>Download backup as text file</a>
  161. </div>
  162. <div>
  163. This is your private key, <b>save it</b>, so you can login next time.<br>
  164. <b>Warning: Without this key, your account will be lost forever!</b>
  165. </div><br>
  166. <a href='#' class='button' style='margin-left: 0px'>Ok, Saved it!</a><br><br>
  167. <small>This site allows you to browse ZeroNet content, but if you want to secure your account <br>
  168. and help to keep the network alive, then please run your own <a href='https://zeronet.io' target='_blank'>ZeroNet client</a>.</small>
  169. """
  170. self.cmd("notification", ["info", message])
  171. script = """
  172. $("#button_notification_masterseed").on("click", function() {
  173. this.value = "{master_seed}"; this.setSelectionRange(0,100);
  174. })
  175. $("#button_notification_download").on("mousedown", function() {
  176. this.href = window.URL.createObjectURL(new Blob(["ZeroNet user master seed:\\r\\n{master_seed}"]))
  177. })
  178. """.replace("{master_seed}", master_seed)
  179. self.cmd("injectScript", script)
  180. def actionPermissionAdd(self, to, permission):
  181. if permission == "NOSANDBOX":
  182. self.cmd("notification", ["info", "You can't disable sandbox on this proxy!"])
  183. self.response(to, {"error": "Denied by proxy"})
  184. return False
  185. else:
  186. return super(UiWebsocketPlugin, self).actionPermissionAdd(to, permission)
  187. @PluginManager.registerTo("ConfigPlugin")
  188. class ConfigPlugin(object):
  189. def createArguments(self):
  190. group = self.parser.add_argument_group("Multiuser plugin")
  191. group.add_argument('--multiuser_local', help="Enable unsafe Ui functions and write users to disk", action='store_true')
  192. group.add_argument('--multiuser_no_new_sites', help="Denies adding new sites by normal users", action='store_true')
  193. return super(ConfigPlugin, self).createArguments()