How to use check_credentials method in tempest

Best Python code snippet using tempest_python

auth.py

Source:auth.py Github

copy

Full Screen

...38 if realm is not None:39 self.realm = realm # shadow class attribute40 self._check_credentials = check_credentials41 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 to46 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 a HTTP 401 error.53 """54 if self._check_credentials is not None:55 return await self._check_credentials(username, password)56 return False57 async def process_request(58 self,59 path: str,60 request_headers: Headers,61 ) -> Optional[HTTPResponse]:62 """63 Check HTTP Basic Auth and return a 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 = username88 return await super().process_request(path, request_headers)89def 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[[Any], BasicAuthWebSocketServerProtocol]] = None,94) -> Callable[[Any], BasicAuthWebSocketServerProtocol]:95 """96 Protocol factory that enforces HTTP Basic Auth.97 :func:`basic_auth_protocol_factory` is designed to integrate with98 :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: indicates the scope of protection. It should contain only ASCII108 characters because the encoding of non-ASCII characters is109 undefined. Refer to section 2.2 of :rfc:`7235` for details.110 credentials: defines hard coded authorized credentials. It can be a111 ``(username, password)`` pair or a list of such pairs.112 check_credentials: defines a coroutine that verifies credentials.113 This coroutine receives ``username`` and ``password`` arguments114 and returns a :class:`bool`. One of ``credentials`` or115 ``check_credentials`` must be provided but not both.116 create_protocol: factory that creates the protocol. By default, this117 is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced118 by a subclass.119 Raises:120 TypeError: if the ``credentials`` or ``check_credentials`` argument is121 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 False140 return hmac.compare_digest(expected_password, password)141 if create_protocol is None:142 # Not sure why mypy cannot figure this out.143 create_protocol = cast(144 Callable[[Any], BasicAuthWebSocketServerProtocol],145 BasicAuthWebSocketServerProtocol,146 )147 return functools.partial(148 create_protocol,149 realm=realm,...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tempest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful