account.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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_handlers().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. if LoginType.PASSWORD in result:
  42. # if using password, they should also be logged in
  43. requester = yield self.auth.get_user_by_req(request)
  44. user_id = requester.user.to_string()
  45. if user_id != result[LoginType.PASSWORD]:
  46. raise LoginError(400, "", Codes.UNKNOWN)
  47. elif LoginType.EMAIL_IDENTITY in result:
  48. threepid = result[LoginType.EMAIL_IDENTITY]
  49. if 'medium' not in threepid or 'address' not in threepid:
  50. raise SynapseError(500, "Malformed threepid")
  51. # if using email, we must know about the email they're authing with!
  52. threepid_user_id = yield self.hs.get_datastore().get_user_id_by_threepid(
  53. threepid['medium'], threepid['address']
  54. )
  55. if not threepid_user_id:
  56. raise SynapseError(404, "Email address not found", Codes.NOT_FOUND)
  57. user_id = threepid_user_id
  58. else:
  59. logger.error("Auth succeeded but no known type!", result.keys())
  60. raise SynapseError(500, "", Codes.UNKNOWN)
  61. if 'new_password' not in params:
  62. raise SynapseError(400, "", Codes.MISSING_PARAM)
  63. new_password = params['new_password']
  64. yield self.auth_handler.set_password(
  65. user_id, new_password, requester
  66. )
  67. defer.returnValue((200, {}))
  68. def on_OPTIONS(self, _):
  69. return 200, {}
  70. class ThreepidRestServlet(RestServlet):
  71. PATTERNS = client_v2_patterns("/account/3pid")
  72. def __init__(self, hs):
  73. super(ThreepidRestServlet, self).__init__()
  74. self.hs = hs
  75. self.identity_handler = hs.get_handlers().identity_handler
  76. self.auth = hs.get_auth()
  77. self.auth_handler = hs.get_handlers().auth_handler
  78. @defer.inlineCallbacks
  79. def on_GET(self, request):
  80. yield run_on_reactor()
  81. requester = yield self.auth.get_user_by_req(request)
  82. threepids = yield self.hs.get_datastore().user_get_threepids(
  83. requester.user.to_string()
  84. )
  85. defer.returnValue((200, {'threepids': threepids}))
  86. @defer.inlineCallbacks
  87. def on_POST(self, request):
  88. yield run_on_reactor()
  89. body = parse_json_object_from_request(request)
  90. threePidCreds = body.get('threePidCreds')
  91. threePidCreds = body.get('three_pid_creds', threePidCreds)
  92. if threePidCreds is None:
  93. raise SynapseError(400, "Missing param", Codes.MISSING_PARAM)
  94. requester = yield self.auth.get_user_by_req(request)
  95. user_id = requester.user.to_string()
  96. threepid = yield self.identity_handler.threepid_from_creds(threePidCreds)
  97. if not threepid:
  98. raise SynapseError(
  99. 400, "Failed to auth 3pid", Codes.THREEPID_AUTH_FAILED
  100. )
  101. for reqd in ['medium', 'address', 'validated_at']:
  102. if reqd not in threepid:
  103. logger.warn("Couldn't add 3pid: invalid response from ID sevrer")
  104. raise SynapseError(500, "Invalid response from ID Server")
  105. yield self.auth_handler.add_threepid(
  106. user_id,
  107. threepid['medium'],
  108. threepid['address'],
  109. threepid['validated_at'],
  110. )
  111. if 'bind' in body and body['bind']:
  112. logger.debug(
  113. "Binding emails %s to %s",
  114. threepid, user_id
  115. )
  116. yield self.identity_handler.bind_threepid(
  117. threePidCreds, user_id
  118. )
  119. defer.returnValue((200, {}))
  120. def register_servlets(hs, http_server):
  121. PasswordRestServlet(hs).register(http_server)
  122. ThreepidRestServlet(hs).register(http_server)