You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

80 lines
2.5 KiB

  1. # Copyright 2017 Vector Creations Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from synapse.api.errors import SynapseError
  16. from synapse.http.servlet import RestServlet, parse_json_object_from_request
  17. from ._base import client_patterns
  18. logger = logging.getLogger(__name__)
  19. class UserDirectorySearchRestServlet(RestServlet):
  20. PATTERNS = client_patterns("/user_directory/search$")
  21. def __init__(self, hs):
  22. """
  23. Args:
  24. hs (synapse.server.HomeServer): server
  25. """
  26. super().__init__()
  27. self.hs = hs
  28. self.auth = hs.get_auth()
  29. self.user_directory_handler = hs.get_user_directory_handler()
  30. async def on_POST(self, request):
  31. """Searches for users in directory
  32. Returns:
  33. dict of the form::
  34. {
  35. "limited": <bool>, # whether there were more results or not
  36. "results": [ # Ordered by best match first
  37. {
  38. "user_id": <user_id>,
  39. "display_name": <display_name>,
  40. "avatar_url": <avatar_url>
  41. }
  42. ]
  43. }
  44. """
  45. requester = await self.auth.get_user_by_req(request, allow_guest=False)
  46. user_id = requester.user.to_string()
  47. if not self.hs.config.user_directory_search_enabled:
  48. return 200, {"limited": False, "results": []}
  49. body = parse_json_object_from_request(request)
  50. limit = body.get("limit", 10)
  51. limit = min(limit, 50)
  52. try:
  53. search_term = body["search_term"]
  54. except Exception:
  55. raise SynapseError(400, "`search_term` is required field")
  56. results = await self.user_directory_handler.search_users(
  57. user_id, search_term, limit
  58. )
  59. return 200, results
  60. def register_servlets(hs, http_server):
  61. UserDirectorySearchRestServlet(hs).register(http_server)