account.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket 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. from twisted.internet import defer
  16. from synapse.api.constants import LoginType
  17. from synapse.api.errors import LoginError, SynapseError, Codes
  18. from synapse.http.servlet import RestServlet, parse_json_object_from_request
  19. from synapse.util.async import run_on_reactor
  20. from ._base import client_v2_patterns
  21. import logging
  22. logger = logging.getLogger(__name__)
  23. class PasswordRestServlet(RestServlet):
  24. PATTERNS = client_v2_patterns("/account/password")
  25. def __init__(self, hs):
  26. super(PasswordRestServlet, self).__init__()
  27. self.hs = hs
  28. self.auth = hs.get_auth()
  29. self.auth_handler = hs.get_auth_handler()
  30. @defer.inlineCallbacks
  31. def on_POST(self, request):
  32. yield run_on_reactor()
  33. body = parse_json_object_from_request(request)
  34. authed, result, params, _ = yield self.auth_handler.check_auth([
  35. [LoginType.PASSWORD],
  36. [LoginType.EMAIL_IDENTITY]
  37. ], body, self.hs.get_ip_from_request(request))
  38. if not authed:
  39. defer.returnValue((401, result))
  40. user_id = None
  41. requester = None
  42. if LoginType.PASSWORD in result:
  43. # if using password, they should also be logged in
  44. requester = yield self.auth.get_user_by_req(request)
  45. user_id = requester.user.to_string()
  46. if user_id != result[LoginType.PASSWORD]:
  47. raise LoginError(400, "", Codes.UNKNOWN)
  48. elif LoginType.EMAIL_IDENTITY in result:
  49. threepid = result[LoginType.EMAIL_IDENTITY]
  50. if 'medium' not in threepid or 'address' not in threepid:
  51. raise SynapseError(500, "Malformed threepid")
  52. # if using email, we must know about the email they're authing with!
  53. threepid_user_id = yield self.hs.get_datastore().get_user_id_by_threepid(
  54. threepid['medium'], threepid['address']
  55. )
  56. if not threepid_user_id:
  57. raise SynapseError(404, "Email address not found", Codes.NOT_FOUND)
  58. user_id = threepid_user_id
  59. else:
  60. logger.error("Auth succeeded but no known type!", result.keys())
  61. raise SynapseError(500, "", Codes.UNKNOWN)
  62. if 'new_password' not in params:
  63. raise SynapseError(400, "", Codes.MISSING_PARAM)
  64. new_password = params['new_password']
  65. yield self.auth_handler.set_password(
  66. user_id, new_password, requester
  67. )
  68. defer.returnValue((200, {}))
  69. def on_OPTIONS(self, _):
  70. return 200, {}
  71. class ThreepidRestServlet(RestServlet):
  72. PATTERNS = client_v2_patterns("/account/3pid")
  73. def __init__(self, hs):
  74. super(ThreepidRestServlet, self).__init__()
  75. self.hs = hs
  76. self.identity_handler = hs.get_handlers().identity_handler
  77. self.auth = hs.get_auth()
  78. self.auth_handler = hs.get_auth_handler()
  79. @defer.inlineCallbacks
  80. def on_GET(self, request):
  81. yield run_on_reactor()
  82. requester = yield self.auth.get_user_by_req(request)
  83. threepids = yield self.hs.get_datastore().user_get_threepids(
  84. requester.user.to_string()
  85. )
  86. defer.returnValue((200, {'threepids': threepids}))
  87. @defer.inlineCallbacks
  88. def on_POST(self, request):
  89. yield run_on_reactor()
  90. body = parse_json_object_from_request(request)
  91. threePidCreds = body.get('threePidCreds')
  92. threePidCreds = body.get('three_pid_creds', threePidCreds)
  93. if threePidCreds is None:
  94. raise SynapseError(400, "Missing param", Codes.MISSING_PARAM)
  95. requester = yield self.auth.get_user_by_req(request)
  96. user_id = requester.user.to_string()
  97. threepid = yield self.identity_handler.threepid_from_creds(threePidCreds)
  98. if not threepid:
  99. raise SynapseError(
  100. 400, "Failed to auth 3pid", Codes.THREEPID_AUTH_FAILED
  101. )
  102. for reqd in ['medium', 'address', 'validated_at']:
  103. if reqd not in threepid:
  104. logger.warn("Couldn't add 3pid: invalid response from ID sevrer")
  105. raise SynapseError(500, "Invalid response from ID Server")
  106. yield self.auth_handler.add_threepid(
  107. user_id,
  108. threepid['medium'],
  109. threepid['address'],
  110. threepid['validated_at'],
  111. )
  112. if 'bind' in body and body['bind']:
  113. logger.debug(
  114. "Binding emails %s to %s",
  115. threepid, user_id
  116. )
  117. yield self.identity_handler.bind_threepid(
  118. threePidCreds, user_id
  119. )
  120. defer.returnValue((200, {}))
  121. def register_servlets(hs, http_server):
  122. PasswordRestServlet(hs).register(http_server)
  123. ThreepidRestServlet(hs).register(http_server)