您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

302 行
12 KiB

  1. # Copyright 2017, 2018 New Vector Ltd
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import TYPE_CHECKING, Optional
  17. from synapse.api.errors import SynapseError
  18. from synapse.handlers.device import DeviceHandler
  19. from synapse.metrics.background_process_metrics import run_as_background_process
  20. from synapse.types import Codes, Requester, UserID, create_requester
  21. if TYPE_CHECKING:
  22. from synapse.server import HomeServer
  23. logger = logging.getLogger(__name__)
  24. class DeactivateAccountHandler:
  25. """Handler which deals with deactivating user accounts."""
  26. def __init__(self, hs: "HomeServer"):
  27. self.store = hs.get_datastores().main
  28. self.hs = hs
  29. self._auth_handler = hs.get_auth_handler()
  30. self._device_handler = hs.get_device_handler()
  31. self._room_member_handler = hs.get_room_member_handler()
  32. self._identity_handler = hs.get_identity_handler()
  33. self._profile_handler = hs.get_profile_handler()
  34. self.user_directory_handler = hs.get_user_directory_handler()
  35. self._server_name = hs.hostname
  36. self._third_party_rules = hs.get_module_api_callbacks().third_party_event_rules
  37. # Flag that indicates whether the process to part users from rooms is running
  38. self._user_parter_running = False
  39. self._third_party_rules = hs.get_module_api_callbacks().third_party_event_rules
  40. # Start the user parter loop so it can resume parting users from rooms where
  41. # it left off (if it has work left to do).
  42. if hs.config.worker.run_background_tasks:
  43. hs.get_reactor().callWhenRunning(self._start_user_parting)
  44. self._account_validity_enabled = (
  45. hs.config.account_validity.account_validity_enabled
  46. )
  47. async def deactivate_account(
  48. self,
  49. user_id: str,
  50. erase_data: bool,
  51. requester: Requester,
  52. id_server: Optional[str] = None,
  53. by_admin: bool = False,
  54. ) -> bool:
  55. """Deactivate a user's account
  56. Args:
  57. user_id: ID of user to be deactivated
  58. erase_data: whether to GDPR-erase the user's data
  59. requester: The user attempting to make this change.
  60. id_server: Use the given identity server when unbinding
  61. any threepids. If None then will attempt to unbind using the
  62. identity server specified when binding (if known).
  63. by_admin: Whether this change was made by an administrator.
  64. Returns:
  65. True if identity server supports removing threepids, otherwise False.
  66. """
  67. # This can only be called on the main process.
  68. assert isinstance(self._device_handler, DeviceHandler)
  69. # Check if this user can be deactivated
  70. if not await self._third_party_rules.check_can_deactivate_user(
  71. user_id, by_admin
  72. ):
  73. raise SynapseError(
  74. 403, "Deactivation of this user is forbidden", Codes.FORBIDDEN
  75. )
  76. # FIXME: Theoretically there is a race here wherein user resets
  77. # password using threepid.
  78. # delete threepids first. We remove these from the IS so if this fails,
  79. # leave the user still active so they can try again.
  80. # Ideally we would prevent password resets and then do this in the
  81. # background thread.
  82. # This will be set to false if the identity server doesn't support
  83. # unbinding
  84. identity_server_supports_unbinding = True
  85. # Attempt to unbind any known bound threepids to this account from identity
  86. # server(s).
  87. bound_threepids = await self.store.user_get_bound_threepids(user_id)
  88. for medium, address in bound_threepids:
  89. try:
  90. result = await self._identity_handler.try_unbind_threepid(
  91. user_id, medium, address, id_server
  92. )
  93. except Exception:
  94. # Do we want this to be a fatal error or should we carry on?
  95. logger.exception("Failed to remove threepid from ID server")
  96. raise SynapseError(400, "Failed to remove threepid from ID server")
  97. identity_server_supports_unbinding &= result
  98. # Remove any local threepid associations for this account.
  99. local_threepids = await self.store.user_get_threepids(user_id)
  100. for local_threepid in local_threepids:
  101. await self._auth_handler.delete_local_threepid(
  102. user_id, local_threepid.medium, local_threepid.address
  103. )
  104. # delete any devices belonging to the user, which will also
  105. # delete corresponding access tokens.
  106. await self._device_handler.delete_all_devices_for_user(user_id)
  107. # then delete any remaining access tokens which weren't associated with
  108. # a device.
  109. await self._auth_handler.delete_access_tokens_for_user(user_id)
  110. await self.store.user_set_password_hash(user_id, None)
  111. # Most of the pushers will have been deleted when we logged out the
  112. # associated devices above, but we still need to delete pushers not
  113. # associated with devices, e.g. email pushers.
  114. await self.store.delete_all_pushers_for_user(user_id)
  115. # Add the user to a table of users pending deactivation (ie.
  116. # removal from all the rooms they're a member of)
  117. await self.store.add_user_pending_deactivation(user_id)
  118. # delete from user directory
  119. await self.user_directory_handler.handle_local_user_deactivated(user_id)
  120. # Mark the user as erased, if they asked for that
  121. if erase_data:
  122. user = UserID.from_string(user_id)
  123. # Remove avatar URL from this user
  124. await self._profile_handler.set_avatar_url(
  125. user, requester, "", by_admin, deactivation=True
  126. )
  127. # Remove displayname from this user
  128. await self._profile_handler.set_displayname(
  129. user, requester, "", by_admin, deactivation=True
  130. )
  131. logger.info("Marking %s as erased", user_id)
  132. await self.store.mark_user_erased(user_id)
  133. # Now start the process that goes through that list and
  134. # parts users from rooms (if it isn't already running)
  135. self._start_user_parting()
  136. # Reject all pending invites for the user, so that the user doesn't show up in the
  137. # "invited" section of rooms' members list.
  138. await self._reject_pending_invites_for_user(user_id)
  139. # Remove all information on the user from the account_validity table.
  140. if self._account_validity_enabled:
  141. await self.store.delete_account_validity_for_user(user_id)
  142. # Mark the user as deactivated.
  143. await self.store.set_user_deactivated_status(user_id, True)
  144. # Remove account data (including ignored users and push rules).
  145. await self.store.purge_account_data_for_user(user_id)
  146. # Delete any server-side backup keys
  147. await self.store.bulk_delete_backup_keys_and_versions_for_user(user_id)
  148. # Let modules know the user has been deactivated.
  149. await self._third_party_rules.on_user_deactivation_status_changed(
  150. user_id,
  151. True,
  152. by_admin,
  153. )
  154. return identity_server_supports_unbinding
  155. async def _reject_pending_invites_for_user(self, user_id: str) -> None:
  156. """Reject pending invites addressed to a given user ID.
  157. Args:
  158. user_id: The user ID to reject pending invites for.
  159. """
  160. user = UserID.from_string(user_id)
  161. pending_invites = await self.store.get_invited_rooms_for_local_user(user_id)
  162. for room in pending_invites:
  163. try:
  164. await self._room_member_handler.update_membership(
  165. create_requester(user, authenticated_entity=self._server_name),
  166. user,
  167. room.room_id,
  168. "leave",
  169. ratelimit=False,
  170. require_consent=False,
  171. )
  172. logger.info(
  173. "Rejected invite for deactivated user %r in room %r",
  174. user_id,
  175. room.room_id,
  176. )
  177. except Exception:
  178. logger.exception(
  179. "Failed to reject invite for user %r in room %r:"
  180. " ignoring and continuing",
  181. user_id,
  182. room.room_id,
  183. )
  184. def _start_user_parting(self) -> None:
  185. """
  186. Start the process that goes through the table of users
  187. pending deactivation, if it isn't already running.
  188. """
  189. if not self._user_parter_running:
  190. run_as_background_process("user_parter_loop", self._user_parter_loop)
  191. async def _user_parter_loop(self) -> None:
  192. """Loop that parts deactivated users from rooms"""
  193. self._user_parter_running = True
  194. logger.info("Starting user parter")
  195. try:
  196. while True:
  197. user_id = await self.store.get_user_pending_deactivation()
  198. if user_id is None:
  199. break
  200. logger.info("User parter parting %r", user_id)
  201. await self._part_user(user_id)
  202. await self.store.del_user_pending_deactivation(user_id)
  203. logger.info("User parter finished parting %r", user_id)
  204. logger.info("User parter finished: stopping")
  205. finally:
  206. self._user_parter_running = False
  207. async def _part_user(self, user_id: str) -> None:
  208. """Causes the given user_id to leave all the rooms they're joined to"""
  209. user = UserID.from_string(user_id)
  210. rooms_for_user = await self.store.get_rooms_for_user(user_id)
  211. for room_id in rooms_for_user:
  212. logger.info("User parter parting %r from %r", user_id, room_id)
  213. try:
  214. await self._room_member_handler.update_membership(
  215. create_requester(user, authenticated_entity=self._server_name),
  216. user,
  217. room_id,
  218. "leave",
  219. ratelimit=False,
  220. require_consent=False,
  221. )
  222. except Exception:
  223. logger.exception(
  224. "Failed to part user %r from room %r: ignoring and continuing",
  225. user_id,
  226. room_id,
  227. )
  228. async def activate_account(self, user_id: str) -> None:
  229. """
  230. Activate an account that was previously deactivated.
  231. This marks the user as active and not erased in the database, but does
  232. not attempt to rejoin rooms, re-add threepids, etc.
  233. If enabled, the user will be re-added to the user directory.
  234. The user will also need a password hash set to actually login.
  235. Args:
  236. user_id: ID of user to be re-activated
  237. """
  238. user = UserID.from_string(user_id)
  239. # Ensure the user is not marked as erased.
  240. await self.store.mark_user_not_erased(user_id)
  241. # Mark the user as active.
  242. await self.store.set_user_deactivated_status(user_id, False)
  243. await self._third_party_rules.on_user_deactivation_status_changed(
  244. user_id, False, True
  245. )
  246. # Add the user to the directory, if necessary. Note that
  247. # this must be done after the user is re-activated, because
  248. # deactivated users are excluded from the user directory.
  249. profile = await self.store.get_profileinfo(user)
  250. await self.user_directory_handler.handle_local_profile_change(user_id, profile)