set_password.py 2.4 KB

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