| 1 |
from abc import ABC, abstractmethod |
| 2 |
from typing import Any, Optional |
| 3 |
|
| 4 |
from django.http import HttpRequest |
| 5 |
|
| 6 |
from ninja.errors import ConfigError |
| 7 |
from ninja.utils import is_async_callable |
| 8 |
|
| 9 |
__all__ = ["SecuritySchema", "AuthBase"] |
| 10 |
|
| 11 |
|
| 12 |
class SecuritySchema(dict): |
| 13 |
def __init__(self, type: str, **kwargs: Any) -> None: |
| 14 |
super().__init__(type=type, **kwargs) |
| 15 |
|
| 16 |
|
| 17 |
class AuthBase(ABC): |
| 18 |
def __init__(self) -> None: |
| 19 |
if not hasattr(self, "openapi_type"): |
| 20 |
raise ConfigError("If you extend AuthBase you need to define openapi_type") |
| 21 |
|
| 22 |
kwargs = {} |
| 23 |
for attr in dir(self): |
| 24 |
if attr.startswith("openapi_"): |
| 25 |
name = attr.replace("openapi_", "", 1) |
| 26 |
kwargs[name] = getattr(self, attr) |
| 27 |
self.openapi_security_schema = SecuritySchema(**kwargs) |
| 28 |
|
| 29 |
self.is_async = False |
| 30 |
if hasattr(self, "authenticate"): |
| 31 |
self.is_async = is_async_callable(self.authenticate) |
| 32 |
|
| 33 |
@abstractmethod |
| 34 |
def __call__(self, request: HttpRequest) -> Optional[Any]: |
| 35 |
pass |