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 8importbase64 9importdataclasses10fromtypesimportMappingProxyType11fromtypingimportLiteral,Union1213from.__version__import*# noqa: F401,F4031415__all__=("Credentials",)1617
[docs]18@dataclasses.dataclass(frozen=True)19classCredentials:20"""Stores access credentials.2122 :param basic: Basic HTTP credentials. If a single :class:`str` is23 given, it is assumed to already be base64-encoded (encoded from24 a :class:`str` of the format ``<user>:<pass>``). If a 2-tuple is25 given, it should be of the form ``(<user>, <pass>)``.26 :type basic: str | tuple[str, str] | None, optional27 :param bearer: Bearer HTTP credentials. If both :paramref:`.basic`28 and :paramref:`.bearer` are defined, :paramref:`.bearer` will be29 used.30 :type bearer: str | None, optional3132 """3334basic:Union[str,tuple[str,str],None]=None35"""See the :paramref:`~Credentials.basic` parameter."""3637bearer:Union[str,None]=None38"""See the :paramref:`~Credentials.bearer` parameter."""3940@staticmethod41def_create_auth_header(42auth_type:Literal["Basic","Bearer"],credentials:str43)->MappingProxyType[str,str]:44"""A helper method that creates the authentication header with45 the given authentication type and credentials.4647 :param auth_type: The authentication type, either ``"Basic"`` or48 ``"Bearer"``.49 :type auth_type: typing.Literal["Basic", "Bearer"]50 :param credentials: The credentials string.51 :type credentials: str5253 :return: The authentication header as an immutable mapping.54 :rtype: types.MappingProxyType[str, str]5556 """57returnMappingProxyType(58{"Authorization":f"{auth_type}{credentials}"}59)60
[docs]61defget_header(self)->MappingProxyType[str,str]:62"""Create the authorization header with the given credentials.63 Result may be empty.6465 :return: The authentication header as an immutable mapping.66 :rtype: ~types.MappingProxyType[str, str]6768 :raises ValueError: If no valid credentials are present.6970 """71ifself.bearerisnotNone:72returnself._create_auth_header("Bearer",self.bearer)73elifisinstance(self.basic,str):74returnself._create_auth_header("Basic",self.basic)75elif(76self.basic77andhasattr(self.basic,"__len__")78andlen(self.basic)==279andall(isinstance(e,str)foreinself.basic)80):81returnself._create_auth_header(82"Basic",83base64.b64encode(":".join(self.basic).encode("ascii")).decode(84"ascii"85),86)87elifself.basic:88raiseValueError("Invalid basic credentials")89else:90returnMappingProxyType({})