deactivate_account.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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.types import UserID, create_requester
  19. from synapse.util.logcontext import run_in_background
  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
  44. """
  45. # FIXME: Theoretically there is a race here wherein user resets
  46. # password using threepid.
  47. # delete threepids first. We remove these from the IS so if this fails,
  48. # leave the user still active so they can try again.
  49. # Ideally we would prevent password resets and then do this in the
  50. # background thread.
  51. threepids = yield self.store.user_get_threepids(user_id)
  52. for threepid in threepids:
  53. try:
  54. yield self._identity_handler.unbind_threepid(
  55. user_id,
  56. {
  57. 'medium': threepid['medium'],
  58. 'address': threepid['address'],
  59. },
  60. )
  61. except Exception:
  62. # Do we want this to be a fatal error or should we carry on?
  63. logger.exception("Failed to remove threepid from ID server")
  64. raise SynapseError(400, "Failed to remove threepid from ID server")
  65. yield self.store.user_delete_threepid(
  66. user_id, threepid['medium'], threepid['address'],
  67. )
  68. # delete any devices belonging to the user, which will also
  69. # delete corresponding access tokens.
  70. yield self._device_handler.delete_all_devices_for_user(user_id)
  71. # then delete any remaining access tokens which weren't associated with
  72. # a device.
  73. yield self._auth_handler.delete_access_tokens_for_user(user_id)
  74. yield self.store.user_set_password_hash(user_id, None)
  75. # Add the user to a table of users pending deactivation (ie.
  76. # removal from all the rooms they're a member of)
  77. yield self.store.add_user_pending_deactivation(user_id)
  78. # delete from user directory
  79. yield self.user_directory_handler.handle_user_deactivated(user_id)
  80. # Mark the user as erased, if they asked for that
  81. if erase_data:
  82. logger.info("Marking %s as erased", user_id)
  83. yield self.store.mark_user_erased(user_id)
  84. # Now start the process that goes through that list and
  85. # parts users from rooms (if it isn't already running)
  86. self._start_user_parting()
  87. def _start_user_parting(self):
  88. """
  89. Start the process that goes through the table of users
  90. pending deactivation, if it isn't already running.
  91. Returns:
  92. None
  93. """
  94. if not self._user_parter_running:
  95. run_in_background(self._user_parter_loop)
  96. @defer.inlineCallbacks
  97. def _user_parter_loop(self):
  98. """Loop that parts deactivated users from rooms
  99. Returns:
  100. None
  101. """
  102. self._user_parter_running = True
  103. logger.info("Starting user parter")
  104. try:
  105. while True:
  106. user_id = yield self.store.get_user_pending_deactivation()
  107. if user_id is None:
  108. break
  109. logger.info("User parter parting %r", user_id)
  110. yield self._part_user(user_id)
  111. yield self.store.del_user_pending_deactivation(user_id)
  112. logger.info("User parter finished parting %r", user_id)
  113. logger.info("User parter finished: stopping")
  114. finally:
  115. self._user_parter_running = False
  116. @defer.inlineCallbacks
  117. def _part_user(self, user_id):
  118. """Causes the given user_id to leave all the rooms they're joined to
  119. Returns:
  120. None
  121. """
  122. user = UserID.from_string(user_id)
  123. rooms_for_user = yield self.store.get_rooms_for_user(user_id)
  124. for room_id in rooms_for_user:
  125. logger.info("User parter parting %r from %r", user_id, room_id)
  126. try:
  127. yield self._room_member_handler.update_membership(
  128. create_requester(user),
  129. user,
  130. room_id,
  131. "leave",
  132. ratelimit=False,
  133. )
  134. except Exception:
  135. logger.exception(
  136. "Failed to part user %r from room %r: ignoring and continuing",
  137. user_id, room_id,
  138. )