__init__.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 New Vector Ltd
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from twisted.internet import defer
  18. from synapse.http.site import SynapseRequest
  19. from synapse.logging.context import make_deferred_yieldable, run_in_background
  20. from synapse.types import UserID
  21. """
  22. This package defines the 'stable' API which can be used by extension modules which
  23. are loaded into Synapse.
  24. """
  25. __all__ = ["errors", "make_deferred_yieldable", "run_in_background", "ModuleApi"]
  26. logger = logging.getLogger(__name__)
  27. class ModuleApi(object):
  28. """A proxy object that gets passed to various plugin modules so they
  29. can register new users etc if necessary.
  30. """
  31. def __init__(self, hs, auth_handler):
  32. self._hs = hs
  33. self._store = hs.get_datastore()
  34. self._auth = hs.get_auth()
  35. self._auth_handler = auth_handler
  36. def get_user_by_req(self, req, allow_guest=False):
  37. """Check the access_token provided for a request
  38. Args:
  39. req (twisted.web.server.Request): Incoming HTTP request
  40. allow_guest (bool): True if guest users should be allowed. If this
  41. is False, and the access token is for a guest user, an
  42. AuthError will be thrown
  43. Returns:
  44. twisted.internet.defer.Deferred[synapse.types.Requester]:
  45. the requester for this request
  46. Raises:
  47. synapse.api.errors.AuthError: if no user by that token exists,
  48. or the token is invalid.
  49. """
  50. return self._auth.get_user_by_req(req, allow_guest)
  51. def get_qualified_user_id(self, username):
  52. """Qualify a user id, if necessary
  53. Takes a user id provided by the user and adds the @ and :domain to
  54. qualify it, if necessary
  55. Args:
  56. username (str): provided user id
  57. Returns:
  58. str: qualified @user:id
  59. """
  60. if username.startswith("@"):
  61. return username
  62. return UserID(username, self._hs.hostname).to_string()
  63. def check_user_exists(self, user_id):
  64. """Check if user exists.
  65. Args:
  66. user_id (str): Complete @user:id
  67. Returns:
  68. Deferred[str|None]: Canonical (case-corrected) user_id, or None
  69. if the user is not registered.
  70. """
  71. return self._auth_handler.check_user_exists(user_id)
  72. @defer.inlineCallbacks
  73. def register(self, localpart, displayname=None, emails=[]):
  74. """Registers a new user with given localpart and optional displayname, emails.
  75. Also returns an access token for the new user.
  76. Deprecated: avoid this, as it generates a new device with no way to
  77. return that device to the user. Prefer separate calls to register_user and
  78. register_device.
  79. Args:
  80. localpart (str): The localpart of the new user.
  81. displayname (str|None): The displayname of the new user.
  82. emails (List[str]): Emails to bind to the new user.
  83. Returns:
  84. Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token)
  85. """
  86. logger.warning(
  87. "Using deprecated ModuleApi.register which creates a dummy user device."
  88. )
  89. user_id = yield self.register_user(localpart, displayname, emails)
  90. _, access_token = yield self.register_device(user_id)
  91. return user_id, access_token
  92. def register_user(self, localpart, displayname=None, emails=[]):
  93. """Registers a new user with given localpart and optional displayname, emails.
  94. Args:
  95. localpart (str): The localpart of the new user.
  96. displayname (str|None): The displayname of the new user.
  97. emails (List[str]): Emails to bind to the new user.
  98. Raises:
  99. SynapseError if there is an error performing the registration. Check the
  100. 'errcode' property for more information on the reason for failure
  101. Returns:
  102. Deferred[str]: user_id
  103. """
  104. return self._hs.get_registration_handler().register_user(
  105. localpart=localpart, default_display_name=displayname, bind_emails=emails
  106. )
  107. def register_device(self, user_id, device_id=None, initial_display_name=None):
  108. """Register a device for a user and generate an access token.
  109. Args:
  110. user_id (str): full canonical @user:id
  111. device_id (str|None): The device ID to check, or None to generate
  112. a new one.
  113. initial_display_name (str|None): An optional display name for the
  114. device.
  115. Returns:
  116. defer.Deferred[tuple[str, str]]: Tuple of device ID and access token
  117. """
  118. return self._hs.get_registration_handler().register_device(
  119. user_id=user_id,
  120. device_id=device_id,
  121. initial_display_name=initial_display_name,
  122. )
  123. def record_user_external_id(
  124. self, auth_provider_id: str, remote_user_id: str, registered_user_id: str
  125. ) -> defer.Deferred:
  126. """Record a mapping from an external user id to a mxid
  127. Args:
  128. auth_provider: identifier for the remote auth provider
  129. external_id: id on that system
  130. user_id: complete mxid that it is mapped to
  131. """
  132. return self._store.record_user_external_id(
  133. auth_provider_id, remote_user_id, registered_user_id
  134. )
  135. def generate_short_term_login_token(
  136. self, user_id: str, duration_in_ms: int = (2 * 60 * 1000)
  137. ) -> str:
  138. """Generate a login token suitable for m.login.token authentication"""
  139. return self._hs.get_macaroon_generator().generate_short_term_login_token(
  140. user_id, duration_in_ms
  141. )
  142. @defer.inlineCallbacks
  143. def invalidate_access_token(self, access_token):
  144. """Invalidate an access token for a user
  145. Args:
  146. access_token(str): access token
  147. Returns:
  148. twisted.internet.defer.Deferred - resolves once the access token
  149. has been removed.
  150. Raises:
  151. synapse.api.errors.AuthError: the access token is invalid
  152. """
  153. # see if the access token corresponds to a device
  154. user_info = yield self._auth.get_user_by_access_token(access_token)
  155. device_id = user_info.get("device_id")
  156. user_id = user_info["user"].to_string()
  157. if device_id:
  158. # delete the device, which will also delete its access tokens
  159. yield self._hs.get_device_handler().delete_device(user_id, device_id)
  160. else:
  161. # no associated device. Just delete the access token.
  162. yield self._auth_handler.delete_access_token(access_token)
  163. def run_db_interaction(self, desc, func, *args, **kwargs):
  164. """Run a function with a database connection
  165. Args:
  166. desc (str): description for the transaction, for metrics etc
  167. func (func): function to be run. Passed a database cursor object
  168. as well as *args and **kwargs
  169. *args: positional args to be passed to func
  170. **kwargs: named args to be passed to func
  171. Returns:
  172. Deferred[object]: result of func
  173. """
  174. return self._store.db.runInteraction(desc, func, *args, **kwargs)
  175. def complete_sso_login(
  176. self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str
  177. ):
  178. """Complete a SSO login by redirecting the user to a page to confirm whether they
  179. want their access token sent to `client_redirect_url`, or redirect them to that
  180. URL with a token directly if the URL matches with one of the whitelisted clients.
  181. Args:
  182. registered_user_id: The MXID that has been registered as a previous step of
  183. of this SSO login.
  184. request: The request to respond to.
  185. client_redirect_url: The URL to which to offer to redirect the user (or to
  186. redirect them directly if whitelisted).
  187. """
  188. self._auth_handler.complete_sso_login(
  189. registered_user_id, request, client_redirect_url,
  190. )