register.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # Copyright 2019 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Optional, Tuple
  16. from twisted.web.server import Request
  17. from synapse.http.server import HttpServer
  18. from synapse.http.servlet import parse_json_object_from_request
  19. from synapse.replication.http._base import ReplicationEndpoint
  20. from synapse.types import JsonDict
  21. if TYPE_CHECKING:
  22. from synapse.server import HomeServer
  23. logger = logging.getLogger(__name__)
  24. class ReplicationRegisterServlet(ReplicationEndpoint):
  25. """Register a new user"""
  26. NAME = "register_user"
  27. PATH_ARGS = ("user_id",)
  28. def __init__(self, hs: "HomeServer"):
  29. super().__init__(hs)
  30. self.store = hs.get_datastores().main
  31. self.registration_handler = hs.get_registration_handler()
  32. # Default value if the worker that sent the replication request did not include
  33. # an 'approved' property.
  34. if (
  35. hs.config.experimental.msc3866.enabled
  36. and hs.config.experimental.msc3866.require_approval_for_new_accounts
  37. ):
  38. self._approval_default = False
  39. else:
  40. self._approval_default = True
  41. @staticmethod
  42. async def _serialize_payload( # type: ignore[override]
  43. user_id: str,
  44. password_hash: Optional[str],
  45. was_guest: bool,
  46. make_guest: bool,
  47. appservice_id: Optional[str],
  48. create_profile_with_displayname: Optional[str],
  49. admin: bool,
  50. user_type: Optional[str],
  51. address: Optional[str],
  52. shadow_banned: bool,
  53. approved: bool,
  54. ) -> JsonDict:
  55. """
  56. Args:
  57. user_id: The desired user ID to register.
  58. password_hash: Optional. The password hash for this user.
  59. was_guest: Optional. Whether this is a guest account being upgraded
  60. to a non-guest account.
  61. make_guest: True if the the new user should be guest, false to add a
  62. regular user account.
  63. appservice_id: The ID of the appservice registering the user.
  64. create_profile_with_displayname: Optionally create a profile for the
  65. user, setting their displayname to the given value
  66. admin: is an admin user?
  67. user_type: type of user. One of the values from api.constants.UserTypes,
  68. or None for a normal user.
  69. address: the IP address used to perform the regitration.
  70. shadow_banned: Whether to shadow-ban the user
  71. approved: Whether the user should be considered already approved by an
  72. administrator.
  73. """
  74. return {
  75. "password_hash": password_hash,
  76. "was_guest": was_guest,
  77. "make_guest": make_guest,
  78. "appservice_id": appservice_id,
  79. "create_profile_with_displayname": create_profile_with_displayname,
  80. "admin": admin,
  81. "user_type": user_type,
  82. "address": address,
  83. "shadow_banned": shadow_banned,
  84. "approved": approved,
  85. }
  86. async def _handle_request( # type: ignore[override]
  87. self, request: Request, user_id: str
  88. ) -> Tuple[int, JsonDict]:
  89. content = parse_json_object_from_request(request)
  90. await self.registration_handler.check_registration_ratelimit(content["address"])
  91. # Always default admin users to approved (since it means they were created by
  92. # an admin).
  93. approved_default = self._approval_default
  94. if content["admin"]:
  95. approved_default = True
  96. await self.registration_handler.register_with_store(
  97. user_id=user_id,
  98. password_hash=content["password_hash"],
  99. was_guest=content["was_guest"],
  100. make_guest=content["make_guest"],
  101. appservice_id=content["appservice_id"],
  102. create_profile_with_displayname=content["create_profile_with_displayname"],
  103. admin=content["admin"],
  104. user_type=content["user_type"],
  105. address=content["address"],
  106. shadow_banned=content["shadow_banned"],
  107. approved=content.get("approved", approved_default),
  108. )
  109. return 200, {}
  110. class ReplicationPostRegisterActionsServlet(ReplicationEndpoint):
  111. """Run any post registration actions"""
  112. NAME = "post_register"
  113. PATH_ARGS = ("user_id",)
  114. def __init__(self, hs: "HomeServer"):
  115. super().__init__(hs)
  116. self.store = hs.get_datastores().main
  117. self.registration_handler = hs.get_registration_handler()
  118. @staticmethod
  119. async def _serialize_payload( # type: ignore[override]
  120. user_id: str, auth_result: JsonDict, access_token: Optional[str]
  121. ) -> JsonDict:
  122. """
  123. Args:
  124. user_id: The user ID that consented
  125. auth_result: The authenticated credentials of the newly registered user.
  126. access_token: The access token of the newly logged in
  127. device, or None if `inhibit_login` enabled.
  128. """
  129. return {"auth_result": auth_result, "access_token": access_token}
  130. async def _handle_request( # type: ignore[override]
  131. self, request: Request, user_id: str
  132. ) -> Tuple[int, JsonDict]:
  133. content = parse_json_object_from_request(request)
  134. auth_result = content["auth_result"]
  135. access_token = content["access_token"]
  136. await self.registration_handler.post_registration_actions(
  137. user_id=user_id, auth_result=auth_result, access_token=access_token
  138. )
  139. return 200, {}
  140. def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
  141. ReplicationRegisterServlet(hs).register(http_server)
  142. ReplicationPostRegisterActionsServlet(hs).register(http_server)