|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +""" |
| 5 | +`adafruit_httpserver.authentication` |
| 6 | +==================================================== |
| 7 | +* Author(s): Michał Pokusa |
| 8 | +""" |
| 9 | + |
| 10 | +try: |
| 11 | + from typing import Union, List |
| 12 | +except ImportError: |
| 13 | + pass |
| 14 | + |
| 15 | +from binascii import b2a_base64 |
| 16 | + |
| 17 | +from .exceptions import AuthenticationError |
| 18 | +from .request import Request |
| 19 | + |
| 20 | + |
| 21 | +class Basic: |
| 22 | + """Represents HTTP Basic Authentication.""" |
| 23 | + |
| 24 | + def __init__(self, username: str, password: str) -> None: |
| 25 | + self._value = b2a_base64(f"{username}:{password}".encode()).decode().strip() |
| 26 | + |
| 27 | + def __str__(self) -> str: |
| 28 | + return f"Basic {self._value}" |
| 29 | + |
| 30 | + |
| 31 | +class Bearer: |
| 32 | + """Represents HTTP Bearer Token Authentication.""" |
| 33 | + |
| 34 | + def __init__(self, token: str) -> None: |
| 35 | + self._value = token |
| 36 | + |
| 37 | + def __str__(self) -> str: |
| 38 | + return f"Bearer {self._value}" |
| 39 | + |
| 40 | + |
| 41 | +def check_authentication(request: Request, auths: List[Union[Basic, Bearer]]) -> bool: |
| 42 | + """ |
| 43 | + Returns ``True`` if request is authorized by any of the authentications, ``False`` otherwise. |
| 44 | + """ |
| 45 | + |
| 46 | + auth_header = request.headers.get("Authorization") |
| 47 | + |
| 48 | + if auth_header is None: |
| 49 | + return False |
| 50 | + |
| 51 | + return any(auth_header == str(auth) for auth in auths) |
| 52 | + |
| 53 | + |
| 54 | +def require_authentication(request: Request, auths: List[Union[Basic, Bearer]]) -> None: |
| 55 | + """ |
| 56 | + Checks if the request is authorized and raises ``AuthenticationError`` if not. |
| 57 | +
|
| 58 | + If the error is not caught, the server will return ``401 Unauthorized``. |
| 59 | + """ |
| 60 | + |
| 61 | + if not check_authentication(request, auths): |
| 62 | + raise AuthenticationError( |
| 63 | + "Request is not authenticated by any of the provided authentications" |
| 64 | + ) |
0 commit comments