Source code for ntfy_api.creds

 1"""A common credentials class used by most of the API wrapper classes.
 2
 3:copyright: (c) 2024 Tanner Corcoran
 4:license: Apache 2.0, see LICENSE for more details.
 5
 6"""
 7
 8import base64
 9import dataclasses
10from types import MappingProxyType
11from typing import Literal, Union
12
13from .__version__ import *  # noqa: F401,F403
14
15__all__ = ("Credentials",)
16
17
[docs] 18@dataclasses.dataclass(frozen=True) 19class Credentials: 20 """Stores access credentials. 21 22 :param basic: Basic HTTP credentials. If a single :class:`str` is 23 given, it is assumed to already be base64-encoded (encoded from 24 a :class:`str` of the format ``<user>:<pass>``). If a 2-tuple is 25 given, it should be of the form ``(<user>, <pass>)``. 26 :type basic: str | tuple[str, str] | None, optional 27 :param bearer: Bearer HTTP credentials. If both :paramref:`.basic` 28 and :paramref:`.bearer` are defined, :paramref:`.bearer` will be 29 used. 30 :type bearer: str | None, optional 31 32 """ 33 34 basic: Union[str, tuple[str, str], None] = None 35 """See the :paramref:`~Credentials.basic` parameter.""" 36 37 bearer: Union[str, None] = None 38 """See the :paramref:`~Credentials.bearer` parameter.""" 39 40 @staticmethod 41 def _create_auth_header( 42 auth_type: Literal["Basic", "Bearer"], credentials: str 43 ) -> MappingProxyType[str, str]: 44 """A helper method that creates the authentication header with 45 the given authentication type and credentials. 46 47 :param auth_type: The authentication type, either ``"Basic"`` or 48 ``"Bearer"``. 49 :type auth_type: typing.Literal["Basic", "Bearer"] 50 :param credentials: The credentials string. 51 :type credentials: str 52 53 :return: The authentication header as an immutable mapping. 54 :rtype: types.MappingProxyType[str, str] 55 56 """ 57 return MappingProxyType( 58 {"Authorization": f"{auth_type} {credentials}"} 59 ) 60
[docs] 61 def get_header(self) -> MappingProxyType[str, str]: 62 """Create the authorization header with the given credentials. 63 Result may be empty. 64 65 :return: The authentication header as an immutable mapping. 66 :rtype: ~types.MappingProxyType[str, str] 67 68 :raises ValueError: If no valid credentials are present. 69 70 """ 71 if self.bearer is not None: 72 return self._create_auth_header("Bearer", self.bearer) 73 elif isinstance(self.basic, str): 74 return self._create_auth_header("Basic", self.basic) 75 elif ( 76 self.basic 77 and hasattr(self.basic, "__len__") 78 and len(self.basic) == 2 79 and all(isinstance(e, str) for e in self.basic) 80 ): 81 return self._create_auth_header( 82 "Basic", 83 base64.b64encode(":".join(self.basic).encode("ascii")).decode( 84 "ascii" 85 ), 86 ) 87 elif self.basic: 88 raise ValueError("Invalid basic credentials") 89 else: 90 return MappingProxyType({})