deactivate_account.py 11 KB

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