| 1 |
import logging |
| 2 |
from abc import ABC, abstractmethod |
| 3 |
from base64 import b64decode |
| 4 |
from typing import Any, Optional, Tuple |
| 5 |
from urllib.parse import unquote |
| 6 |
|
| 7 |
from django.conf import settings |
| 8 |
from django.http import HttpRequest |
| 9 |
|
| 10 |
from ninja.security.base import AuthBase |
| 11 |
|
| 12 |
__all__ = ["HttpAuthBase", "HttpBearer", "DecodeError", "HttpBasicAuth"] |
| 13 |
|
| 14 |
|
| 15 |
logger = logging.getLogger("django") |
| 16 |
|
| 17 |
|
| 18 |
class HttpAuthBase(AuthBase, ABC): |
| 19 |
openapi_type: str = "http" |
| 20 |
|
| 21 |
|
| 22 |
class HttpBearer(HttpAuthBase, ABC): |
| 23 |
openapi_scheme: str = "bearer" |
| 24 |
header: str = "Authorization" |
| 25 |
|
| 26 |
def __call__(self, request: HttpRequest) -> Optional[Any]: |
| 27 |
headers = request.headers |
| 28 |
auth_value = headers.get(self.header) |
| 29 |
if not auth_value: |
| 30 |
return None |
| 31 |
parts = auth_value.split(" ") |
| 32 |
|
| 33 |
if parts[0].lower() != self.openapi_scheme: |
| 34 |
if settings.DEBUG: |
| 35 |
logger.error(f"Unexpected auth - '{auth_value}'") |
| 36 |
return None |
| 37 |
token = " ".join(parts[1:]) |
| 38 |
return self.authenticate(request, token) |
| 39 |
|
| 40 |
@abstractmethod |
| 41 |
def authenticate(self, request: HttpRequest, token: str) -> Optional[Any]: |
| 42 |
pass |
| 43 |
|
| 44 |
|
| 45 |
class DecodeError(Exception): |
| 46 |
pass |
| 47 |
|
| 48 |
|
| 49 |
class HttpBasicAuth(HttpAuthBase, ABC): |
| 50 |
openapi_scheme = "basic" |
| 51 |
header = "Authorization" |
| 52 |
|
| 53 |
def __call__(self, request: HttpRequest) -> Optional[Any]: |
| 54 |
headers = request.headers |
| 55 |
auth_value = headers.get(self.header) |
| 56 |
if not auth_value: |
| 57 |
return None |
| 58 |
|
| 59 |
try: |
| 60 |
username, password = self.decode_authorization(auth_value) |
| 61 |
except DecodeError as e: |
| 62 |
if settings.DEBUG: |
| 63 |
logger.exception(e) |
| 64 |
return None |
| 65 |
return self.authenticate(request, username, password) |
| 66 |
|
| 67 |
@abstractmethod |
| 68 |
def authenticate( |
| 69 |
self, request: HttpRequest, username: str, password: str |
| 70 |
) -> Optional[Any]: |
| 71 |
pass |
| 72 |
|
| 73 |
def decode_authorization(self, value: str) -> Tuple[str, str]: |
| 74 |
parts = value.split(" ") |
| 75 |
if len(parts) == 1: |
| 76 |
user_pass_encoded = parts[0] |
| 77 |
elif len(parts) == 2 and parts[0].lower() == "basic": |
| 78 |
user_pass_encoded = parts[1] |
| 79 |
else: |
| 80 |
raise DecodeError("Invalid Authorization header") |
| 81 |
|
| 82 |
try: |
| 83 |
username, password = b64decode(user_pass_encoded).decode().split(":", 1) |
| 84 |
return unquote(username), unquote(password) |
| 85 |
except Exception as e: |
| 86 |
raise DecodeError("Invalid Authorization header") from e |