__init__.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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.types import UserID
  18. logger = logging.getLogger(__name__)
  19. class ModuleApi(object):
  20. """A proxy object that gets passed to password auth providers so they
  21. can register new users etc if necessary.
  22. """
  23. def __init__(self, hs, auth_handler):
  24. self.hs = hs
  25. self._store = hs.get_datastore()
  26. self._auth = hs.get_auth()
  27. self._auth_handler = auth_handler
  28. def get_user_by_req(self, req, allow_guest=False):
  29. """Check the access_token provided for a request
  30. Args:
  31. req (twisted.web.server.Request): Incoming HTTP request
  32. allow_guest (bool): True if guest users should be allowed. If this
  33. is False, and the access token is for a guest user, an
  34. AuthError will be thrown
  35. Returns:
  36. twisted.internet.defer.Deferred[synapse.types.Requester]:
  37. the requester for this request
  38. Raises:
  39. synapse.api.errors.AuthError: if no user by that token exists,
  40. or the token is invalid.
  41. """
  42. return self._auth.get_user_by_req(req, allow_guest)
  43. def get_qualified_user_id(self, username):
  44. """Qualify a user id, if necessary
  45. Takes a user id provided by the user and adds the @ and :domain to
  46. qualify it, if necessary
  47. Args:
  48. username (str): provided user id
  49. Returns:
  50. str: qualified @user:id
  51. """
  52. if username.startswith("@"):
  53. return username
  54. return UserID(username, self.hs.hostname).to_string()
  55. def check_user_exists(self, user_id):
  56. """Check if user exists.
  57. Args:
  58. user_id (str): Complete @user:id
  59. Returns:
  60. Deferred[str|None]: Canonical (case-corrected) user_id, or None
  61. if the user is not registered.
  62. """
  63. return self._auth_handler.check_user_exists(user_id)
  64. @defer.inlineCallbacks
  65. def register(self, localpart, displayname=None, emails=[]):
  66. """Registers a new user with given localpart and optional displayname, emails.
  67. Also returns an access token for the new user.
  68. Deprecated: avoid this, as it generates a new device with no way to
  69. return that device to the user. Prefer separate calls to register_user and
  70. register_device.
  71. Args:
  72. localpart (str): The localpart of the new user.
  73. displayname (str|None): The displayname of the new user.
  74. emails (List[str]): Emails to bind to the new user.
  75. Returns:
  76. Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token)
  77. """
  78. logger.warning(
  79. "Using deprecated ModuleApi.register which creates a dummy user device."
  80. )
  81. user_id = yield self.register_user(localpart, displayname, emails)
  82. _, access_token = yield self.register_device(user_id)
  83. return (user_id, access_token)
  84. def register_user(self, localpart, displayname=None, emails=[]):
  85. """Registers a new user with given localpart and optional displayname, emails.
  86. Args:
  87. localpart (str): The localpart of the new user.
  88. displayname (str|None): The displayname of the new user.
  89. emails (List[str]): Emails to bind to the new user.
  90. Returns:
  91. Deferred[str]: user_id
  92. """
  93. return self.hs.get_registration_handler().register_user(
  94. localpart=localpart, default_display_name=displayname, bind_emails=emails
  95. )
  96. def register_device(self, user_id, device_id=None, initial_display_name=None):
  97. """Register a device for a user and generate an access token.
  98. Args:
  99. user_id (str): full canonical @user:id
  100. device_id (str|None): The device ID to check, or None to generate
  101. a new one.
  102. initial_display_name (str|None): An optional display name for the
  103. device.
  104. Returns:
  105. defer.Deferred[tuple[str, str]]: Tuple of device ID and access token
  106. """
  107. return self.hs.get_registration_handler().register_device(
  108. user_id=user_id,
  109. device_id=device_id,
  110. initial_display_name=initial_display_name,
  111. )
  112. @defer.inlineCallbacks
  113. def invalidate_access_token(self, access_token):
  114. """Invalidate an access token for a user
  115. Args:
  116. access_token(str): access token
  117. Returns:
  118. twisted.internet.defer.Deferred - resolves once the access token
  119. has been removed.
  120. Raises:
  121. synapse.api.errors.AuthError: the access token is invalid
  122. """
  123. # see if the access token corresponds to a device
  124. user_info = yield self._auth.get_user_by_access_token(access_token)
  125. device_id = user_info.get("device_id")
  126. user_id = user_info["user"].to_string()
  127. if device_id:
  128. # delete the device, which will also delete its access tokens
  129. yield self.hs.get_device_handler().delete_device(user_id, device_id)
  130. else:
  131. # no associated device. Just delete the access token.
  132. yield self._auth_handler.delete_access_token(access_token)
  133. def run_db_interaction(self, desc, func, *args, **kwargs):
  134. """Run a function with a database connection
  135. Args:
  136. desc (str): description for the transaction, for metrics etc
  137. func (func): function to be run. Passed a database cursor object
  138. as well as *args and **kwargs
  139. *args: positional args to be passed to func
  140. **kwargs: named args to be passed to func
  141. Returns:
  142. Deferred[object]: result of func
  143. """
  144. return self._store.runInteraction(desc, func, *args, **kwargs)