You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

70 regels
2.6 KiB

  1. # Copyright 2017 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
  16. from synapse.api.errors import Codes, StoreError, SynapseError
  17. from synapse.handlers.device import DeviceHandler
  18. from synapse.types import Requester
  19. if TYPE_CHECKING:
  20. from synapse.server import HomeServer
  21. logger = logging.getLogger(__name__)
  22. class SetPasswordHandler:
  23. """Handler which deals with changing user account passwords"""
  24. def __init__(self, hs: "HomeServer"):
  25. self.store = hs.get_datastores().main
  26. self._auth_handler = hs.get_auth_handler()
  27. # This can only be instantiated on the main process.
  28. device_handler = hs.get_device_handler()
  29. assert isinstance(device_handler, DeviceHandler)
  30. self._device_handler = device_handler
  31. async def set_password(
  32. self,
  33. user_id: str,
  34. password_hash: str,
  35. logout_devices: bool,
  36. requester: Optional[Requester] = None,
  37. ) -> None:
  38. if not self._auth_handler.can_change_password():
  39. raise SynapseError(403, "Password change disabled", errcode=Codes.FORBIDDEN)
  40. try:
  41. await self.store.user_set_password_hash(user_id, password_hash)
  42. except StoreError as e:
  43. if e.code == 404:
  44. raise SynapseError(404, "Unknown user", Codes.NOT_FOUND)
  45. raise e
  46. # Optionally, log out all of the user's other sessions.
  47. if logout_devices:
  48. except_device_id = requester.device_id if requester else None
  49. except_access_token_id = requester.access_token_id if requester else None
  50. # First delete all of their other devices.
  51. await self._device_handler.delete_all_devices_for_user(
  52. user_id, except_device_id=except_device_id
  53. )
  54. # and now delete any access tokens which weren't associated with
  55. # devices (or were associated with this device).
  56. await self._auth_handler.delete_access_tokens_for_user(
  57. user_id, except_token_id=except_access_token_id
  58. )