set_password.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 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 Codes, StoreError, SynapseError
  18. from ._base import BaseHandler
  19. logger = logging.getLogger(__name__)
  20. class SetPasswordHandler(BaseHandler):
  21. """Handler which deals with changing user account passwords"""
  22. def __init__(self, hs):
  23. super(SetPasswordHandler, self).__init__(hs)
  24. self._auth_handler = hs.get_auth_handler()
  25. self._device_handler = hs.get_device_handler()
  26. @defer.inlineCallbacks
  27. def set_password(self, user_id, newpassword, requester=None):
  28. password_hash = yield self._auth_handler.hash(newpassword)
  29. except_device_id = requester.device_id if requester else None
  30. except_access_token_id = requester.access_token_id if requester else None
  31. try:
  32. yield self.store.user_set_password_hash(user_id, password_hash)
  33. except StoreError as e:
  34. if e.code == 404:
  35. raise SynapseError(404, "Unknown user", Codes.NOT_FOUND)
  36. raise e
  37. # we want to log out all of the user's other sessions. First delete
  38. # all his other devices.
  39. yield self._device_handler.delete_all_devices_for_user(
  40. user_id, except_device_id=except_device_id,
  41. )
  42. # and now delete any access tokens which weren't associated with
  43. # devices (or were associated with this device).
  44. yield self._auth_handler.delete_access_tokens_for_user(
  45. user_id, except_token_id=except_access_token_id,
  46. )