account.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  4. # Copyright 2018 New Vector Ltd
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. from http import HTTPStatus
  19. from synapse.api.constants import LoginType
  20. from synapse.api.errors import Codes, SynapseError, ThreepidValidationError
  21. from synapse.config.emailconfig import ThreepidBehaviour
  22. from synapse.http.server import finish_request
  23. from synapse.http.servlet import (
  24. RestServlet,
  25. assert_params_in_dict,
  26. parse_json_object_from_request,
  27. parse_string,
  28. )
  29. from synapse.push.mailer import Mailer, load_jinja2_templates
  30. from synapse.util.msisdn import phone_number_to_msisdn
  31. from synapse.util.stringutils import assert_valid_client_secret, random_string
  32. from synapse.util.threepids import check_3pid_allowed
  33. from ._base import client_patterns, interactive_auth_handler
  34. logger = logging.getLogger(__name__)
  35. class EmailPasswordRequestTokenRestServlet(RestServlet):
  36. PATTERNS = client_patterns("/account/password/email/requestToken$")
  37. def __init__(self, hs):
  38. super(EmailPasswordRequestTokenRestServlet, self).__init__()
  39. self.hs = hs
  40. self.datastore = hs.get_datastore()
  41. self.config = hs.config
  42. self.identity_handler = hs.get_handlers().identity_handler
  43. if self.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  44. template_html, template_text = load_jinja2_templates(
  45. self.config.email_template_dir,
  46. [
  47. self.config.email_password_reset_template_html,
  48. self.config.email_password_reset_template_text,
  49. ],
  50. apply_format_ts_filter=True,
  51. apply_mxc_to_http_filter=True,
  52. public_baseurl=self.config.public_baseurl,
  53. )
  54. self.mailer = Mailer(
  55. hs=self.hs,
  56. app_name=self.config.email_app_name,
  57. template_html=template_html,
  58. template_text=template_text,
  59. )
  60. async def on_POST(self, request):
  61. if self.config.threepid_behaviour_email == ThreepidBehaviour.OFF:
  62. if self.config.local_threepid_handling_disabled_due_to_email_config:
  63. logger.warning(
  64. "User password resets have been disabled due to lack of email config"
  65. )
  66. raise SynapseError(
  67. 400, "Email-based password resets have been disabled on this server"
  68. )
  69. body = parse_json_object_from_request(request)
  70. assert_params_in_dict(body, ["client_secret", "email", "send_attempt"])
  71. # Extract params from body
  72. client_secret = body["client_secret"]
  73. assert_valid_client_secret(client_secret)
  74. email = body["email"]
  75. send_attempt = body["send_attempt"]
  76. next_link = body.get("next_link") # Optional param
  77. if not check_3pid_allowed(self.hs, "email", email):
  78. raise SynapseError(
  79. 403,
  80. "Your email domain is not authorized on this server",
  81. Codes.THREEPID_DENIED,
  82. )
  83. existing_user_id = await self.hs.get_datastore().get_user_id_by_threepid(
  84. "email", email
  85. )
  86. if existing_user_id is None:
  87. if self.config.request_token_inhibit_3pid_errors:
  88. # Make the client think the operation succeeded. See the rationale in the
  89. # comments for request_token_inhibit_3pid_errors.
  90. return 200, {"sid": random_string(16)}
  91. raise SynapseError(400, "Email not found", Codes.THREEPID_NOT_FOUND)
  92. if self.config.threepid_behaviour_email == ThreepidBehaviour.REMOTE:
  93. assert self.hs.config.account_threepid_delegate_email
  94. # Have the configured identity server handle the request
  95. ret = await self.identity_handler.requestEmailToken(
  96. self.hs.config.account_threepid_delegate_email,
  97. email,
  98. client_secret,
  99. send_attempt,
  100. next_link,
  101. )
  102. else:
  103. # Send password reset emails from Synapse
  104. sid = await self.identity_handler.send_threepid_validation(
  105. email,
  106. client_secret,
  107. send_attempt,
  108. self.mailer.send_password_reset_mail,
  109. next_link,
  110. )
  111. # Wrap the session id in a JSON object
  112. ret = {"sid": sid}
  113. return 200, ret
  114. class PasswordResetSubmitTokenServlet(RestServlet):
  115. """Handles 3PID validation token submission"""
  116. PATTERNS = client_patterns(
  117. "/password_reset/(?P<medium>[^/]*)/submit_token$", releases=(), unstable=True
  118. )
  119. def __init__(self, hs):
  120. """
  121. Args:
  122. hs (synapse.server.HomeServer): server
  123. """
  124. super(PasswordResetSubmitTokenServlet, self).__init__()
  125. self.hs = hs
  126. self.auth = hs.get_auth()
  127. self.config = hs.config
  128. self.clock = hs.get_clock()
  129. self.store = hs.get_datastore()
  130. if self.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  131. (self.failure_email_template,) = load_jinja2_templates(
  132. self.config.email_template_dir,
  133. [self.config.email_password_reset_template_failure_html],
  134. )
  135. async def on_GET(self, request, medium):
  136. # We currently only handle threepid token submissions for email
  137. if medium != "email":
  138. raise SynapseError(
  139. 400, "This medium is currently not supported for password resets"
  140. )
  141. if self.config.threepid_behaviour_email == ThreepidBehaviour.OFF:
  142. if self.config.local_threepid_handling_disabled_due_to_email_config:
  143. logger.warning(
  144. "Password reset emails have been disabled due to lack of an email config"
  145. )
  146. raise SynapseError(
  147. 400, "Email-based password resets are disabled on this server"
  148. )
  149. sid = parse_string(request, "sid", required=True)
  150. token = parse_string(request, "token", required=True)
  151. client_secret = parse_string(request, "client_secret", required=True)
  152. assert_valid_client_secret(client_secret)
  153. # Attempt to validate a 3PID session
  154. try:
  155. # Mark the session as valid
  156. next_link = await self.store.validate_threepid_session(
  157. sid, client_secret, token, self.clock.time_msec()
  158. )
  159. # Perform a 302 redirect if next_link is set
  160. if next_link:
  161. if next_link.startswith("file:///"):
  162. logger.warning(
  163. "Not redirecting to next_link as it is a local file: address"
  164. )
  165. else:
  166. request.setResponseCode(302)
  167. request.setHeader("Location", next_link)
  168. finish_request(request)
  169. return None
  170. # Otherwise show the success template
  171. html = self.config.email_password_reset_template_success_html
  172. request.setResponseCode(200)
  173. except ThreepidValidationError as e:
  174. request.setResponseCode(e.code)
  175. # Show a failure page with a reason
  176. template_vars = {"failure_reason": e.msg}
  177. html = self.failure_email_template.render(**template_vars)
  178. request.write(html.encode("utf-8"))
  179. finish_request(request)
  180. class PasswordRestServlet(RestServlet):
  181. PATTERNS = client_patterns("/account/password$")
  182. def __init__(self, hs):
  183. super(PasswordRestServlet, self).__init__()
  184. self.hs = hs
  185. self.auth = hs.get_auth()
  186. self.auth_handler = hs.get_auth_handler()
  187. self.datastore = self.hs.get_datastore()
  188. self.password_policy_handler = hs.get_password_policy_handler()
  189. self._set_password_handler = hs.get_set_password_handler()
  190. @interactive_auth_handler
  191. async def on_POST(self, request):
  192. body = parse_json_object_from_request(request)
  193. # we do basic sanity checks here because the auth layer will store these
  194. # in sessions. Pull out the new password provided to us.
  195. if "new_password" in body:
  196. new_password = body.pop("new_password")
  197. if not isinstance(new_password, str) or len(new_password) > 512:
  198. raise SynapseError(400, "Invalid password")
  199. self.password_policy_handler.validate_password(new_password)
  200. # If the password is valid, hash it and store it back on the body.
  201. # This ensures that only the hashed password is handled everywhere.
  202. if "new_password_hash" in body:
  203. raise SynapseError(400, "Unexpected property: new_password_hash")
  204. body["new_password_hash"] = await self.auth_handler.hash(new_password)
  205. # there are two possibilities here. Either the user does not have an
  206. # access token, and needs to do a password reset; or they have one and
  207. # need to validate their identity.
  208. #
  209. # In the first case, we offer a couple of means of identifying
  210. # themselves (email and msisdn, though it's unclear if msisdn actually
  211. # works).
  212. #
  213. # In the second case, we require a password to confirm their identity.
  214. if self.auth.has_access_token(request):
  215. requester = await self.auth.get_user_by_req(request)
  216. params = await self.auth_handler.validate_user_via_ui_auth(
  217. requester,
  218. request,
  219. body,
  220. self.hs.get_ip_from_request(request),
  221. "modify your account password",
  222. )
  223. user_id = requester.user.to_string()
  224. else:
  225. requester = None
  226. result, params, _ = await self.auth_handler.check_auth(
  227. [[LoginType.EMAIL_IDENTITY]],
  228. request,
  229. body,
  230. self.hs.get_ip_from_request(request),
  231. "modify your account password",
  232. )
  233. if LoginType.EMAIL_IDENTITY in result:
  234. threepid = result[LoginType.EMAIL_IDENTITY]
  235. if "medium" not in threepid or "address" not in threepid:
  236. raise SynapseError(500, "Malformed threepid")
  237. if threepid["medium"] == "email":
  238. # For emails, transform the address to lowercase.
  239. # We store all email addreses as lowercase in the DB.
  240. # (See add_threepid in synapse/handlers/auth.py)
  241. threepid["address"] = threepid["address"].lower()
  242. # if using email, we must know about the email they're authing with!
  243. threepid_user_id = await self.datastore.get_user_id_by_threepid(
  244. threepid["medium"], threepid["address"]
  245. )
  246. if not threepid_user_id:
  247. raise SynapseError(404, "Email address not found", Codes.NOT_FOUND)
  248. user_id = threepid_user_id
  249. else:
  250. logger.error("Auth succeeded but no known type! %r", result.keys())
  251. raise SynapseError(500, "", Codes.UNKNOWN)
  252. assert_params_in_dict(params, ["new_password_hash"])
  253. new_password_hash = params["new_password_hash"]
  254. logout_devices = params.get("logout_devices", True)
  255. await self._set_password_handler.set_password(
  256. user_id, new_password_hash, logout_devices, requester
  257. )
  258. return 200, {}
  259. def on_OPTIONS(self, _):
  260. return 200, {}
  261. class DeactivateAccountRestServlet(RestServlet):
  262. PATTERNS = client_patterns("/account/deactivate$")
  263. def __init__(self, hs):
  264. super(DeactivateAccountRestServlet, self).__init__()
  265. self.hs = hs
  266. self.auth = hs.get_auth()
  267. self.auth_handler = hs.get_auth_handler()
  268. self._deactivate_account_handler = hs.get_deactivate_account_handler()
  269. @interactive_auth_handler
  270. async def on_POST(self, request):
  271. body = parse_json_object_from_request(request)
  272. erase = body.get("erase", False)
  273. if not isinstance(erase, bool):
  274. raise SynapseError(
  275. HTTPStatus.BAD_REQUEST,
  276. "Param 'erase' must be a boolean, if given",
  277. Codes.BAD_JSON,
  278. )
  279. requester = await self.auth.get_user_by_req(request)
  280. # allow ASes to dectivate their own users
  281. if requester.app_service:
  282. await self._deactivate_account_handler.deactivate_account(
  283. requester.user.to_string(), erase
  284. )
  285. return 200, {}
  286. await self.auth_handler.validate_user_via_ui_auth(
  287. requester,
  288. request,
  289. body,
  290. self.hs.get_ip_from_request(request),
  291. "deactivate your account",
  292. )
  293. result = await self._deactivate_account_handler.deactivate_account(
  294. requester.user.to_string(), erase, id_server=body.get("id_server")
  295. )
  296. if result:
  297. id_server_unbind_result = "success"
  298. else:
  299. id_server_unbind_result = "no-support"
  300. return 200, {"id_server_unbind_result": id_server_unbind_result}
  301. class EmailThreepidRequestTokenRestServlet(RestServlet):
  302. PATTERNS = client_patterns("/account/3pid/email/requestToken$")
  303. def __init__(self, hs):
  304. super(EmailThreepidRequestTokenRestServlet, self).__init__()
  305. self.hs = hs
  306. self.config = hs.config
  307. self.identity_handler = hs.get_handlers().identity_handler
  308. self.store = self.hs.get_datastore()
  309. if self.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  310. template_html, template_text = load_jinja2_templates(
  311. self.config.email_template_dir,
  312. [
  313. self.config.email_add_threepid_template_html,
  314. self.config.email_add_threepid_template_text,
  315. ],
  316. public_baseurl=self.config.public_baseurl,
  317. )
  318. self.mailer = Mailer(
  319. hs=self.hs,
  320. app_name=self.config.email_app_name,
  321. template_html=template_html,
  322. template_text=template_text,
  323. )
  324. async def on_POST(self, request):
  325. if self.config.threepid_behaviour_email == ThreepidBehaviour.OFF:
  326. if self.config.local_threepid_handling_disabled_due_to_email_config:
  327. logger.warning(
  328. "Adding emails have been disabled due to lack of an email config"
  329. )
  330. raise SynapseError(
  331. 400, "Adding an email to your account is disabled on this server"
  332. )
  333. body = parse_json_object_from_request(request)
  334. assert_params_in_dict(body, ["client_secret", "email", "send_attempt"])
  335. client_secret = body["client_secret"]
  336. assert_valid_client_secret(client_secret)
  337. email = body["email"]
  338. send_attempt = body["send_attempt"]
  339. next_link = body.get("next_link") # Optional param
  340. if not check_3pid_allowed(self.hs, "email", email):
  341. raise SynapseError(
  342. 403,
  343. "Your email domain is not authorized on this server",
  344. Codes.THREEPID_DENIED,
  345. )
  346. existing_user_id = await self.store.get_user_id_by_threepid(
  347. "email", body["email"]
  348. )
  349. if existing_user_id is not None:
  350. if self.config.request_token_inhibit_3pid_errors:
  351. # Make the client think the operation succeeded. See the rationale in the
  352. # comments for request_token_inhibit_3pid_errors.
  353. return 200, {"sid": random_string(16)}
  354. raise SynapseError(400, "Email is already in use", Codes.THREEPID_IN_USE)
  355. if self.config.threepid_behaviour_email == ThreepidBehaviour.REMOTE:
  356. assert self.hs.config.account_threepid_delegate_email
  357. # Have the configured identity server handle the request
  358. ret = await self.identity_handler.requestEmailToken(
  359. self.hs.config.account_threepid_delegate_email,
  360. email,
  361. client_secret,
  362. send_attempt,
  363. next_link,
  364. )
  365. else:
  366. # Send threepid validation emails from Synapse
  367. sid = await self.identity_handler.send_threepid_validation(
  368. email,
  369. client_secret,
  370. send_attempt,
  371. self.mailer.send_add_threepid_mail,
  372. next_link,
  373. )
  374. # Wrap the session id in a JSON object
  375. ret = {"sid": sid}
  376. return 200, ret
  377. class MsisdnThreepidRequestTokenRestServlet(RestServlet):
  378. PATTERNS = client_patterns("/account/3pid/msisdn/requestToken$")
  379. def __init__(self, hs):
  380. self.hs = hs
  381. super(MsisdnThreepidRequestTokenRestServlet, self).__init__()
  382. self.store = self.hs.get_datastore()
  383. self.identity_handler = hs.get_handlers().identity_handler
  384. async def on_POST(self, request):
  385. body = parse_json_object_from_request(request)
  386. assert_params_in_dict(
  387. body, ["client_secret", "country", "phone_number", "send_attempt"]
  388. )
  389. client_secret = body["client_secret"]
  390. assert_valid_client_secret(client_secret)
  391. country = body["country"]
  392. phone_number = body["phone_number"]
  393. send_attempt = body["send_attempt"]
  394. next_link = body.get("next_link") # Optional param
  395. msisdn = phone_number_to_msisdn(country, phone_number)
  396. if not check_3pid_allowed(self.hs, "msisdn", msisdn):
  397. raise SynapseError(
  398. 403,
  399. "Account phone numbers are not authorized on this server",
  400. Codes.THREEPID_DENIED,
  401. )
  402. existing_user_id = await self.store.get_user_id_by_threepid("msisdn", msisdn)
  403. if existing_user_id is not None:
  404. if self.hs.config.request_token_inhibit_3pid_errors:
  405. # Make the client think the operation succeeded. See the rationale in the
  406. # comments for request_token_inhibit_3pid_errors.
  407. return 200, {"sid": random_string(16)}
  408. raise SynapseError(400, "MSISDN is already in use", Codes.THREEPID_IN_USE)
  409. if not self.hs.config.account_threepid_delegate_msisdn:
  410. logger.warning(
  411. "No upstream msisdn account_threepid_delegate configured on the server to "
  412. "handle this request"
  413. )
  414. raise SynapseError(
  415. 400,
  416. "Adding phone numbers to user account is not supported by this homeserver",
  417. )
  418. ret = await self.identity_handler.requestMsisdnToken(
  419. self.hs.config.account_threepid_delegate_msisdn,
  420. country,
  421. phone_number,
  422. client_secret,
  423. send_attempt,
  424. next_link,
  425. )
  426. return 200, ret
  427. class AddThreepidEmailSubmitTokenServlet(RestServlet):
  428. """Handles 3PID validation token submission for adding an email to a user's account"""
  429. PATTERNS = client_patterns(
  430. "/add_threepid/email/submit_token$", releases=(), unstable=True
  431. )
  432. def __init__(self, hs):
  433. """
  434. Args:
  435. hs (synapse.server.HomeServer): server
  436. """
  437. super().__init__()
  438. self.config = hs.config
  439. self.clock = hs.get_clock()
  440. self.store = hs.get_datastore()
  441. if self.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  442. (self.failure_email_template,) = load_jinja2_templates(
  443. self.config.email_template_dir,
  444. [self.config.email_add_threepid_template_failure_html],
  445. )
  446. async def on_GET(self, request):
  447. if self.config.threepid_behaviour_email == ThreepidBehaviour.OFF:
  448. if self.config.local_threepid_handling_disabled_due_to_email_config:
  449. logger.warning(
  450. "Adding emails have been disabled due to lack of an email config"
  451. )
  452. raise SynapseError(
  453. 400, "Adding an email to your account is disabled on this server"
  454. )
  455. elif self.config.threepid_behaviour_email == ThreepidBehaviour.REMOTE:
  456. raise SynapseError(
  457. 400,
  458. "This homeserver is not validating threepids. Use an identity server "
  459. "instead.",
  460. )
  461. sid = parse_string(request, "sid", required=True)
  462. token = parse_string(request, "token", required=True)
  463. client_secret = parse_string(request, "client_secret", required=True)
  464. assert_valid_client_secret(client_secret)
  465. # Attempt to validate a 3PID session
  466. try:
  467. # Mark the session as valid
  468. next_link = await self.store.validate_threepid_session(
  469. sid, client_secret, token, self.clock.time_msec()
  470. )
  471. # Perform a 302 redirect if next_link is set
  472. if next_link:
  473. if next_link.startswith("file:///"):
  474. logger.warning(
  475. "Not redirecting to next_link as it is a local file: address"
  476. )
  477. else:
  478. request.setResponseCode(302)
  479. request.setHeader("Location", next_link)
  480. finish_request(request)
  481. return None
  482. # Otherwise show the success template
  483. html = self.config.email_add_threepid_template_success_html_content
  484. request.setResponseCode(200)
  485. except ThreepidValidationError as e:
  486. request.setResponseCode(e.code)
  487. # Show a failure page with a reason
  488. template_vars = {"failure_reason": e.msg}
  489. html = self.failure_email_template.render(**template_vars)
  490. request.write(html.encode("utf-8"))
  491. finish_request(request)
  492. class AddThreepidMsisdnSubmitTokenServlet(RestServlet):
  493. """Handles 3PID validation token submission for adding a phone number to a user's
  494. account
  495. """
  496. PATTERNS = client_patterns(
  497. "/add_threepid/msisdn/submit_token$", releases=(), unstable=True
  498. )
  499. def __init__(self, hs):
  500. """
  501. Args:
  502. hs (synapse.server.HomeServer): server
  503. """
  504. super().__init__()
  505. self.config = hs.config
  506. self.clock = hs.get_clock()
  507. self.store = hs.get_datastore()
  508. self.identity_handler = hs.get_handlers().identity_handler
  509. async def on_POST(self, request):
  510. if not self.config.account_threepid_delegate_msisdn:
  511. raise SynapseError(
  512. 400,
  513. "This homeserver is not validating phone numbers. Use an identity server "
  514. "instead.",
  515. )
  516. body = parse_json_object_from_request(request)
  517. assert_params_in_dict(body, ["client_secret", "sid", "token"])
  518. assert_valid_client_secret(body["client_secret"])
  519. # Proxy submit_token request to msisdn threepid delegate
  520. response = await self.identity_handler.proxy_msisdn_submit_token(
  521. self.config.account_threepid_delegate_msisdn,
  522. body["client_secret"],
  523. body["sid"],
  524. body["token"],
  525. )
  526. return 200, response
  527. class ThreepidRestServlet(RestServlet):
  528. PATTERNS = client_patterns("/account/3pid$")
  529. def __init__(self, hs):
  530. super(ThreepidRestServlet, self).__init__()
  531. self.hs = hs
  532. self.identity_handler = hs.get_handlers().identity_handler
  533. self.auth = hs.get_auth()
  534. self.auth_handler = hs.get_auth_handler()
  535. self.datastore = self.hs.get_datastore()
  536. async def on_GET(self, request):
  537. requester = await self.auth.get_user_by_req(request)
  538. threepids = await self.datastore.user_get_threepids(requester.user.to_string())
  539. return 200, {"threepids": threepids}
  540. async def on_POST(self, request):
  541. if not self.hs.config.enable_3pid_changes:
  542. raise SynapseError(
  543. 400, "3PID changes are disabled on this server", Codes.FORBIDDEN
  544. )
  545. requester = await self.auth.get_user_by_req(request)
  546. user_id = requester.user.to_string()
  547. body = parse_json_object_from_request(request)
  548. threepid_creds = body.get("threePidCreds") or body.get("three_pid_creds")
  549. if threepid_creds is None:
  550. raise SynapseError(
  551. 400, "Missing param three_pid_creds", Codes.MISSING_PARAM
  552. )
  553. assert_params_in_dict(threepid_creds, ["client_secret", "sid"])
  554. sid = threepid_creds["sid"]
  555. client_secret = threepid_creds["client_secret"]
  556. assert_valid_client_secret(client_secret)
  557. validation_session = await self.identity_handler.validate_threepid_session(
  558. client_secret, sid
  559. )
  560. if validation_session:
  561. await self.auth_handler.add_threepid(
  562. user_id,
  563. validation_session["medium"],
  564. validation_session["address"],
  565. validation_session["validated_at"],
  566. )
  567. return 200, {}
  568. raise SynapseError(
  569. 400, "No validated 3pid session found", Codes.THREEPID_AUTH_FAILED
  570. )
  571. class ThreepidAddRestServlet(RestServlet):
  572. PATTERNS = client_patterns("/account/3pid/add$")
  573. def __init__(self, hs):
  574. super(ThreepidAddRestServlet, self).__init__()
  575. self.hs = hs
  576. self.identity_handler = hs.get_handlers().identity_handler
  577. self.auth = hs.get_auth()
  578. self.auth_handler = hs.get_auth_handler()
  579. @interactive_auth_handler
  580. async def on_POST(self, request):
  581. if not self.hs.config.enable_3pid_changes:
  582. raise SynapseError(
  583. 400, "3PID changes are disabled on this server", Codes.FORBIDDEN
  584. )
  585. requester = await self.auth.get_user_by_req(request)
  586. user_id = requester.user.to_string()
  587. body = parse_json_object_from_request(request)
  588. assert_params_in_dict(body, ["client_secret", "sid"])
  589. sid = body["sid"]
  590. client_secret = body["client_secret"]
  591. assert_valid_client_secret(client_secret)
  592. await self.auth_handler.validate_user_via_ui_auth(
  593. requester,
  594. request,
  595. body,
  596. self.hs.get_ip_from_request(request),
  597. "add a third-party identifier to your account",
  598. )
  599. validation_session = await self.identity_handler.validate_threepid_session(
  600. client_secret, sid
  601. )
  602. if validation_session:
  603. await self.auth_handler.add_threepid(
  604. user_id,
  605. validation_session["medium"],
  606. validation_session["address"],
  607. validation_session["validated_at"],
  608. )
  609. return 200, {}
  610. raise SynapseError(
  611. 400, "No validated 3pid session found", Codes.THREEPID_AUTH_FAILED
  612. )
  613. class ThreepidBindRestServlet(RestServlet):
  614. PATTERNS = client_patterns("/account/3pid/bind$")
  615. def __init__(self, hs):
  616. super(ThreepidBindRestServlet, self).__init__()
  617. self.hs = hs
  618. self.identity_handler = hs.get_handlers().identity_handler
  619. self.auth = hs.get_auth()
  620. async def on_POST(self, request):
  621. body = parse_json_object_from_request(request)
  622. assert_params_in_dict(body, ["id_server", "sid", "client_secret"])
  623. id_server = body["id_server"]
  624. sid = body["sid"]
  625. id_access_token = body.get("id_access_token") # optional
  626. client_secret = body["client_secret"]
  627. assert_valid_client_secret(client_secret)
  628. requester = await self.auth.get_user_by_req(request)
  629. user_id = requester.user.to_string()
  630. await self.identity_handler.bind_threepid(
  631. client_secret, sid, user_id, id_server, id_access_token
  632. )
  633. return 200, {}
  634. class ThreepidUnbindRestServlet(RestServlet):
  635. PATTERNS = client_patterns("/account/3pid/unbind$")
  636. def __init__(self, hs):
  637. super(ThreepidUnbindRestServlet, self).__init__()
  638. self.hs = hs
  639. self.identity_handler = hs.get_handlers().identity_handler
  640. self.auth = hs.get_auth()
  641. self.datastore = self.hs.get_datastore()
  642. async def on_POST(self, request):
  643. """Unbind the given 3pid from a specific identity server, or identity servers that are
  644. known to have this 3pid bound
  645. """
  646. requester = await self.auth.get_user_by_req(request)
  647. body = parse_json_object_from_request(request)
  648. assert_params_in_dict(body, ["medium", "address"])
  649. medium = body.get("medium")
  650. address = body.get("address")
  651. id_server = body.get("id_server")
  652. # Attempt to unbind the threepid from an identity server. If id_server is None, try to
  653. # unbind from all identity servers this threepid has been added to in the past
  654. result = await self.identity_handler.try_unbind_threepid(
  655. requester.user.to_string(),
  656. {"address": address, "medium": medium, "id_server": id_server},
  657. )
  658. return 200, {"id_server_unbind_result": "success" if result else "no-support"}
  659. class ThreepidDeleteRestServlet(RestServlet):
  660. PATTERNS = client_patterns("/account/3pid/delete$")
  661. def __init__(self, hs):
  662. super(ThreepidDeleteRestServlet, self).__init__()
  663. self.hs = hs
  664. self.auth = hs.get_auth()
  665. self.auth_handler = hs.get_auth_handler()
  666. async def on_POST(self, request):
  667. if not self.hs.config.enable_3pid_changes:
  668. raise SynapseError(
  669. 400, "3PID changes are disabled on this server", Codes.FORBIDDEN
  670. )
  671. body = parse_json_object_from_request(request)
  672. assert_params_in_dict(body, ["medium", "address"])
  673. requester = await self.auth.get_user_by_req(request)
  674. user_id = requester.user.to_string()
  675. try:
  676. ret = await self.auth_handler.delete_threepid(
  677. user_id, body["medium"], body["address"], body.get("id_server")
  678. )
  679. except Exception:
  680. # NB. This endpoint should succeed if there is nothing to
  681. # delete, so it should only throw if something is wrong
  682. # that we ought to care about.
  683. logger.exception("Failed to remove threepid")
  684. raise SynapseError(500, "Failed to remove threepid")
  685. if ret:
  686. id_server_unbind_result = "success"
  687. else:
  688. id_server_unbind_result = "no-support"
  689. return 200, {"id_server_unbind_result": id_server_unbind_result}
  690. class WhoamiRestServlet(RestServlet):
  691. PATTERNS = client_patterns("/account/whoami$")
  692. def __init__(self, hs):
  693. super(WhoamiRestServlet, self).__init__()
  694. self.auth = hs.get_auth()
  695. async def on_GET(self, request):
  696. requester = await self.auth.get_user_by_req(request)
  697. return 200, {"user_id": requester.user.to_string()}
  698. def register_servlets(hs, http_server):
  699. EmailPasswordRequestTokenRestServlet(hs).register(http_server)
  700. PasswordResetSubmitTokenServlet(hs).register(http_server)
  701. PasswordRestServlet(hs).register(http_server)
  702. DeactivateAccountRestServlet(hs).register(http_server)
  703. EmailThreepidRequestTokenRestServlet(hs).register(http_server)
  704. MsisdnThreepidRequestTokenRestServlet(hs).register(http_server)
  705. AddThreepidEmailSubmitTokenServlet(hs).register(http_server)
  706. AddThreepidMsisdnSubmitTokenServlet(hs).register(http_server)
  707. ThreepidRestServlet(hs).register(http_server)
  708. ThreepidAddRestServlet(hs).register(http_server)
  709. ThreepidBindRestServlet(hs).register(http_server)
  710. ThreepidUnbindRestServlet(hs).register(http_server)
  711. ThreepidDeleteRestServlet(hs).register(http_server)
  712. WhoamiRestServlet(hs).register(http_server)