Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

107 строки
3.4 KiB

  1. # Copyright 2014-2016 OpenMarket 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. """This module contains base REST classes for constructing client v1 servlets.
  15. """
  16. import logging
  17. import re
  18. from typing import Any, Awaitable, Callable, Iterable, Pattern, Tuple, TypeVar, cast
  19. from synapse.api.errors import InteractiveAuthIncompleteError
  20. from synapse.api.urls import CLIENT_API_PREFIX
  21. from synapse.types import JsonDict, StrCollection
  22. logger = logging.getLogger(__name__)
  23. def client_patterns(
  24. path_regex: str,
  25. releases: StrCollection = ("r0", "v3"),
  26. unstable: bool = True,
  27. v1: bool = False,
  28. ) -> Iterable[Pattern]:
  29. """Creates a regex compiled client path with the correct client path
  30. prefix.
  31. Args:
  32. path_regex: The regex string to match. This should NOT have a ^
  33. as this will be prefixed.
  34. releases: An iterable of releases to include this endpoint under.
  35. unstable: If true, include this endpoint under the "unstable" prefix.
  36. v1: If true, include this endpoint under the "api/v1" prefix.
  37. Returns:
  38. An iterable of patterns.
  39. """
  40. versions = []
  41. if v1:
  42. versions.append("api/v1")
  43. versions.extend(releases)
  44. if unstable:
  45. versions.append("unstable")
  46. if len(versions) == 1:
  47. versions_str = versions[0]
  48. elif len(versions) > 1:
  49. versions_str = "(" + "|".join(versions) + ")"
  50. else:
  51. raise RuntimeError("Must have at least one version for a URL")
  52. return [re.compile("^" + CLIENT_API_PREFIX + "/" + versions_str + path_regex)]
  53. def set_timeline_upper_limit(filter_json: JsonDict, filter_timeline_limit: int) -> None:
  54. """
  55. Enforces a maximum limit of a timeline query.
  56. Params:
  57. filter_json: The timeline query to modify.
  58. filter_timeline_limit: The maximum limit to allow, passing -1 will
  59. disable enforcing a maximum limit.
  60. """
  61. if filter_timeline_limit < 0:
  62. return # no upper limits
  63. timeline = filter_json.get("room", {}).get("timeline", {})
  64. if "limit" in timeline:
  65. filter_json["room"]["timeline"]["limit"] = min(
  66. filter_json["room"]["timeline"]["limit"], filter_timeline_limit
  67. )
  68. C = TypeVar("C", bound=Callable[..., Awaitable[Tuple[int, JsonDict]]])
  69. def interactive_auth_handler(orig: C) -> C:
  70. """Wraps an on_POST method to handle InteractiveAuthIncompleteErrors
  71. Takes a on_POST method which returns an Awaitable (errcode, body) response
  72. and adds exception handling to turn a InteractiveAuthIncompleteError into
  73. a 401 response.
  74. Normal usage is:
  75. @interactive_auth_handler
  76. async def on_POST(self, request):
  77. # ...
  78. await self.auth_handler.check_auth
  79. """
  80. async def wrapped(*args: Any, **kwargs: Any) -> Tuple[int, JsonDict]:
  81. try:
  82. return await orig(*args, **kwargs)
  83. except InteractiveAuthIncompleteError as e:
  84. return 401, e.result
  85. return cast(C, wrapped)