|
| 1 | +from utcp.data.auth import Auth |
| 2 | +from utcp.interfaces.serializer import Serializer |
| 3 | +from pydantic import Field, ValidationError |
| 4 | +from typing import Literal |
| 5 | +from utcp.exceptions import UtcpSerializerValidationError |
| 6 | + |
| 7 | +class ApiKeyAuth(Auth): |
| 8 | + """Authentication using an API key. |
| 9 | +
|
| 10 | + The key can be provided directly or sourced from an environment variable. |
| 11 | + Supports placement in headers, query parameters, or cookies. |
| 12 | +
|
| 13 | + Attributes: |
| 14 | + auth_type: The authentication type identifier, always "api_key". |
| 15 | + api_key: The API key for authentication. Values starting with '$' or formatted as '${}' are |
| 16 | + treated as an injected variable from environment or configuration. |
| 17 | + var_name: The name of the header, query parameter, or cookie that |
| 18 | + contains the API key. |
| 19 | + location: Where to include the API key (header, query parameter, or cookie). |
| 20 | + """ |
| 21 | + |
| 22 | + auth_type: Literal["api_key"] = "api_key" |
| 23 | + api_key: str = Field(..., description="The API key for authentication. Values starting with '$' or formatted as '${}' are treated as an injected variable from environment or configuration. This is the recommended way to provide API keys.") |
| 24 | + var_name: str = Field( |
| 25 | + "X-Api-Key", description="The name of the header, query parameter, cookie or other container for the API key." |
| 26 | + ) |
| 27 | + location: Literal["header", "query", "cookie"] = Field( |
| 28 | + "header", description="Where to include the API key (header, query parameter, or cookie)." |
| 29 | + ) |
| 30 | + |
| 31 | + |
| 32 | +class ApiKeyAuthSerializer(Serializer[ApiKeyAuth]): |
| 33 | + def to_dict(self, obj: ApiKeyAuth) -> dict: |
| 34 | + return obj.model_dump() |
| 35 | + |
| 36 | + def validate_dict(self, obj: dict) -> ApiKeyAuth: |
| 37 | + try: |
| 38 | + return ApiKeyAuth.model_validate(obj) |
| 39 | + except ValidationError as e: |
| 40 | + raise UtcpSerializerValidationError(f"Invalid ApiKeyAuth: {e}") from e |
| 41 | + except Exception as e: |
| 42 | + raise UtcpSerializerValidationError("An unexpected error occurred during ApiKeyAuth validation.") from e |
0 commit comments