deactivate_account.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017, 2018 New Vector Ltd
  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 twisted.internet import defer
  17. from synapse.api.errors import SynapseError
  18. from synapse.metrics.background_process_metrics import run_as_background_process
  19. from synapse.types import UserID, create_requester
  20. from ._base import BaseHandler
  21. logger = logging.getLogger(__name__)
  22. class DeactivateAccountHandler(BaseHandler):
  23. """Handler which deals with deactivating user accounts."""
  24. def __init__(self, hs):
  25. super(DeactivateAccountHandler, self).__init__(hs)
  26. self._auth_handler = hs.get_auth_handler()
  27. self._device_handler = hs.get_device_handler()
  28. self._room_member_handler = hs.get_room_member_handler()
  29. self._identity_handler = hs.get_handlers().identity_handler
  30. self.user_directory_handler = hs.get_user_directory_handler()
  31. # Flag that indicates whether the process to part users from rooms is running
  32. self._user_parter_running = False
  33. # Start the user parter loop so it can resume parting users from rooms where
  34. # it left off (if it has work left to do).
  35. hs.get_reactor().callWhenRunning(self._start_user_parting)
  36. @defer.inlineCallbacks
  37. def deactivate_account(self, user_id, erase_data):
  38. """Deactivate a user's account
  39. Args:
  40. user_id (str): ID of user to be deactivated
  41. erase_data (bool): whether to GDPR-erase the user's data
  42. Returns:
  43. Deferred[bool]: True if identity server supports removing
  44. threepids, otherwise False.
  45. """
  46. # FIXME: Theoretically there is a race here wherein user resets
  47. # password using threepid.
  48. # delete threepids first. We remove these from the IS so if this fails,
  49. # leave the user still active so they can try again.
  50. # Ideally we would prevent password resets and then do this in the
  51. # background thread.
  52. # This will be set to false if the identity server doesn't support
  53. # unbinding
  54. identity_server_supports_unbinding = True
  55. threepids = yield self.store.user_get_threepids(user_id)
  56. for threepid in threepids:
  57. try:
  58. result = yield self._identity_handler.try_unbind_threepid(
  59. user_id,
  60. {
  61. 'medium': threepid['medium'],
  62. 'address': threepid['address'],
  63. },
  64. )
  65. identity_server_supports_unbinding &= result
  66. except Exception:
  67. # Do we want this to be a fatal error or should we carry on?
  68. logger.exception("Failed to remove threepid from ID server")
  69. raise SynapseError(400, "Failed to remove threepid from ID server")
  70. yield self.store.user_delete_threepid(
  71. user_id, threepid['medium'], threepid['address'],
  72. )
  73. # delete any devices belonging to the user, which will also
  74. # delete corresponding access tokens.
  75. yield self._device_handler.delete_all_devices_for_user(user_id)
  76. # then delete any remaining access tokens which weren't associated with
  77. # a device.
  78. yield self._auth_handler.delete_access_tokens_for_user(user_id)
  79. yield self.store.user_set_password_hash(user_id, None)
  80. # Add the user to a table of users pending deactivation (ie.
  81. # removal from all the rooms they're a member of)
  82. yield self.store.add_user_pending_deactivation(user_id)
  83. # delete from user directory
  84. yield self.user_directory_handler.handle_user_deactivated(user_id)
  85. # Mark the user as erased, if they asked for that
  86. if erase_data:
  87. logger.info("Marking %s as erased", user_id)
  88. yield self.store.mark_user_erased(user_id)
  89. # Now start the process that goes through that list and
  90. # parts users from rooms (if it isn't already running)
  91. self._start_user_parting()
  92. defer.returnValue(identity_server_supports_unbinding)
  93. def _start_user_parting(self):
  94. """
  95. Start the process that goes through the table of users
  96. pending deactivation, if it isn't already running.
  97. Returns:
  98. None
  99. """
  100. if not self._user_parter_running:
  101. run_as_background_process("user_parter_loop", self._user_parter_loop)
  102. @defer.inlineCallbacks
  103. def _user_parter_loop(self):
  104. """Loop that parts deactivated users from rooms
  105. Returns:
  106. None
  107. """
  108. self._user_parter_running = True
  109. logger.info("Starting user parter")
  110. try:
  111. while True:
  112. user_id = yield self.store.get_user_pending_deactivation()
  113. if user_id is None:
  114. break
  115. logger.info("User parter parting %r", user_id)
  116. yield self._part_user(user_id)
  117. yield self.store.del_user_pending_deactivation(user_id)
  118. logger.info("User parter finished parting %r", user_id)
  119. logger.info("User parter finished: stopping")
  120. finally:
  121. self._user_parter_running = False
  122. @defer.inlineCallbacks
  123. def _part_user(self, user_id):
  124. """Causes the given user_id to leave all the rooms they're joined to
  125. Returns:
  126. None
  127. """
  128. user = UserID.from_string(user_id)
  129. rooms_for_user = yield self.store.get_rooms_for_user(user_id)
  130. for room_id in rooms_for_user:
  131. logger.info("User parter parting %r from %r", user_id, room_id)
  132. try:
  133. yield self._room_member_handler.update_membership(
  134. create_requester(user),
  135. user,
  136. room_id,
  137. "leave",
  138. ratelimit=False,
  139. )
  140. except Exception:
  141. logger.exception(
  142. "Failed to part user %r from room %r: ignoring and continuing",
  143. user_id, room_id,
  144. )