Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

auth.py 6.1KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from __future__ import annotations
  2. import functools
  3. import hmac
  4. import http
  5. from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
  6. from ..datastructures import Headers
  7. from ..exceptions import InvalidHeader
  8. from ..headers import build_www_authenticate_basic, parse_authorization_basic
  9. from .server import HTTPResponse, WebSocketServerProtocol
  10. __all__ = ["BasicAuthWebSocketServerProtocol", "basic_auth_protocol_factory"]
  11. Credentials = Tuple[str, str]
  12. def is_credentials(value: Any) -> bool:
  13. try:
  14. username, password = value
  15. except (TypeError, ValueError):
  16. return False
  17. else:
  18. return isinstance(username, str) and isinstance(password, str)
  19. class BasicAuthWebSocketServerProtocol(WebSocketServerProtocol):
  20. """
  21. WebSocket server protocol that enforces HTTP Basic Auth.
  22. """
  23. realm: str = ""
  24. """
  25. Scope of protection.
  26. If provided, it should contain only ASCII characters because the
  27. encoding of non-ASCII characters is undefined.
  28. """
  29. username: Optional[str] = None
  30. """Username of the authenticated user."""
  31. def __init__(
  32. self,
  33. *args: Any,
  34. realm: Optional[str] = None,
  35. check_credentials: Optional[Callable[[str, str], Awaitable[bool]]] = None,
  36. **kwargs: Any,
  37. ) -> None:
  38. if realm is not None:
  39. self.realm = realm # shadow class attribute
  40. self._check_credentials = check_credentials
  41. super().__init__(*args, **kwargs)
  42. async def check_credentials(self, username: str, password: str) -> bool:
  43. """
  44. Check whether credentials are authorized.
  45. This coroutine may be overridden in a subclass, for example to
  46. authenticate against a database or an external service.
  47. Args:
  48. username: HTTP Basic Auth username.
  49. password: HTTP Basic Auth password.
  50. Returns:
  51. bool: :obj:`True` if the handshake should continue;
  52. :obj:`False` if it should fail with an HTTP 401 error.
  53. """
  54. if self._check_credentials is not None:
  55. return await self._check_credentials(username, password)
  56. return False
  57. async def process_request(
  58. self,
  59. path: str,
  60. request_headers: Headers,
  61. ) -> Optional[HTTPResponse]:
  62. """
  63. Check HTTP Basic Auth and return an HTTP 401 response if needed.
  64. """
  65. try:
  66. authorization = request_headers["Authorization"]
  67. except KeyError:
  68. return (
  69. http.HTTPStatus.UNAUTHORIZED,
  70. [("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
  71. b"Missing credentials\n",
  72. )
  73. try:
  74. username, password = parse_authorization_basic(authorization)
  75. except InvalidHeader:
  76. return (
  77. http.HTTPStatus.UNAUTHORIZED,
  78. [("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
  79. b"Unsupported credentials\n",
  80. )
  81. if not await self.check_credentials(username, password):
  82. return (
  83. http.HTTPStatus.UNAUTHORIZED,
  84. [("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
  85. b"Invalid credentials\n",
  86. )
  87. self.username = username
  88. return await super().process_request(path, request_headers)
  89. def basic_auth_protocol_factory(
  90. realm: Optional[str] = None,
  91. credentials: Optional[Union[Credentials, Iterable[Credentials]]] = None,
  92. check_credentials: Optional[Callable[[str, str], Awaitable[bool]]] = None,
  93. create_protocol: Optional[Callable[..., BasicAuthWebSocketServerProtocol]] = None,
  94. ) -> Callable[..., BasicAuthWebSocketServerProtocol]:
  95. """
  96. Protocol factory that enforces HTTP Basic Auth.
  97. :func:`basic_auth_protocol_factory` is designed to integrate with
  98. :func:`~websockets.server.serve` like this::
  99. websockets.serve(
  100. ...,
  101. create_protocol=websockets.basic_auth_protocol_factory(
  102. realm="my dev server",
  103. credentials=("hello", "iloveyou"),
  104. )
  105. )
  106. Args:
  107. realm: Scope of protection. It should contain only ASCII characters
  108. because the encoding of non-ASCII characters is undefined.
  109. Refer to section 2.2 of :rfc:`7235` for details.
  110. credentials: Hard coded authorized credentials. It can be a
  111. ``(username, password)`` pair or a list of such pairs.
  112. check_credentials: Coroutine that verifies credentials.
  113. It receives ``username`` and ``password`` arguments
  114. and returns a :class:`bool`. One of ``credentials`` or
  115. ``check_credentials`` must be provided but not both.
  116. create_protocol: Factory that creates the protocol. By default, this
  117. is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced
  118. by a subclass.
  119. Raises:
  120. TypeError: If the ``credentials`` or ``check_credentials`` argument is
  121. wrong.
  122. """
  123. if (credentials is None) == (check_credentials is None):
  124. raise TypeError("provide either credentials or check_credentials")
  125. if credentials is not None:
  126. if is_credentials(credentials):
  127. credentials_list = [cast(Credentials, credentials)]
  128. elif isinstance(credentials, Iterable):
  129. credentials_list = list(credentials)
  130. if not all(is_credentials(item) for item in credentials_list):
  131. raise TypeError(f"invalid credentials argument: {credentials}")
  132. else:
  133. raise TypeError(f"invalid credentials argument: {credentials}")
  134. credentials_dict = dict(credentials_list)
  135. async def check_credentials(username: str, password: str) -> bool:
  136. try:
  137. expected_password = credentials_dict[username]
  138. except KeyError:
  139. return False
  140. return hmac.compare_digest(expected_password, password)
  141. if create_protocol is None:
  142. create_protocol = BasicAuthWebSocketServerProtocol
  143. return functools.partial(
  144. create_protocol,
  145. realm=realm,
  146. check_credentials=check_credentials,
  147. )