tools2fast-fastapi 0.3.13__tar.gz → 0.3.14__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {tools2fast_fastapi-0.3.13/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.3.14}/PKG-INFO +58 -1
- tools2fast_fastapi-0.3.14/README.md +95 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/__init__.py +4 -0
- tools2fast_fastapi-0.3.14/src/tools2fast_fastapi/__version__.py +1 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/__init__.py +4 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/response_schema.py +131 -2
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/skills/SKILL.md +9 -1
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14/src/tools2fast_fastapi.egg-info}/PKG-INFO +58 -1
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/SOURCES.txt +1 -0
- tools2fast_fastapi-0.3.14/tests/test_auth_error.py +184 -0
- tools2fast_fastapi-0.3.13/README.md +0 -38
- tools2fast_fastapi-0.3.13/src/tools2fast_fastapi/__version__.py +0 -1
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/LICENSE +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/MANIFEST.in +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/docs/guide.md +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/examples/example.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/pyproject.toml +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/setup.cfg +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/models/__init__.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/models/mixins.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/mixins.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/__init__.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/document_simple_revision_service.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/document_with_items_revision_service.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/number_service.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/query_filters.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/revision_service.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/transaction_service.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/utils/__init__.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/utils/routing.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/tests/test_initial.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/tests/test_query_filters.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/tests/test_response_schema.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/tests/test_revision_service.py +0 -0
- {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/tests/test_schemas.py +0 -0
{tools2fast_fastapi-0.3.13/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.3.14}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tools2fast-fastapi
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.14
|
|
4
4
|
Summary: Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use
|
|
5
5
|
Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -69,8 +69,65 @@ uv pip install -e path/to/tools2fast-fastapi
|
|
|
69
69
|
|
|
70
70
|
- **SQLModel Mixins**: Standardized `IdMixin`, `TimestampMixin`, and `AuditMixin`.
|
|
71
71
|
- **Base Models**: Core models setup to be inherited across all entity definitions.
|
|
72
|
+
- **Unified API envelope**: Success and error helpers via `APIResponse`.
|
|
73
|
+
- **Auth error helper**: `APIResponse.auth_error(...)` returns a ready-to-return
|
|
74
|
+
`JSONResponse` with the project envelope and, for HTTP 401, the RFC 6750
|
|
75
|
+
`WWW-Authenticate` header.
|
|
72
76
|
- **Shared Services**: Reusable services logic for basic CRUD and related queries (coming soon).
|
|
73
77
|
|
|
78
|
+
## Auth error contract
|
|
79
|
+
|
|
80
|
+
`APIResponse.auth_error` produces a stable contract for authentication and
|
|
81
|
+
authorization failures. The discriminator is `error.type` (never the message),
|
|
82
|
+
which lets clients react without string matching:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from tools2fast_fastapi import APIResponse
|
|
86
|
+
|
|
87
|
+
return APIResponse.auth_error(
|
|
88
|
+
error_code="TokenExpired",
|
|
89
|
+
message="Token expirado",
|
|
90
|
+
status_code=401,
|
|
91
|
+
www_authenticate='Bearer error="expired_token"',
|
|
92
|
+
)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
When the failure happens inside a **FastAPI dependency**, return a `Response`
|
|
96
|
+
is not enough (FastAPI injects it as the dependency value instead of
|
|
97
|
+
short-circuiting). Raise `AuthError` and register the handler once at startup:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from fastapi import FastAPI
|
|
101
|
+
from tools2fast_fastapi import AuthError, install_auth_error_handler
|
|
102
|
+
|
|
103
|
+
app = FastAPI()
|
|
104
|
+
install_auth_error_handler(app)
|
|
105
|
+
|
|
106
|
+
async def get_current_user(...):
|
|
107
|
+
raise AuthError(
|
|
108
|
+
error_code="TokenExpired",
|
|
109
|
+
message="Token expirado",
|
|
110
|
+
www_authenticate='Bearer error="expired_token"',
|
|
111
|
+
)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Both paths produce the same envelope and the same RFC 6750 header.
|
|
115
|
+
|
|
116
|
+
| Situation | Status | `error.type` | `WWW-Authenticate` |
|
|
117
|
+
|---|---|---|---|
|
|
118
|
+
| Missing token | 401 | `TokenMissing` | `Bearer` |
|
|
119
|
+
| Malformed / bad signature | 401 | `TokenInvalid` | `Bearer error="invalid_token"` |
|
|
120
|
+
| Expired token | 401 | `TokenExpired` | `Bearer error="expired_token"` |
|
|
121
|
+
| Email not verified | 403 | `EmailNotVerified` | — |
|
|
122
|
+
| Missing permission | 403 | `PermissionDenied` | — |
|
|
123
|
+
| Missing role | 403 | `RoleMissing` | — |
|
|
124
|
+
| Valid token, no tenant | 403 | `TenantRequired` | — |
|
|
125
|
+
| Inactive tenant | 403 | `TenantInactive` | — |
|
|
126
|
+
|
|
127
|
+
When `status_code` is `401` and `www_authenticate` is omitted, the header
|
|
128
|
+
defaults to `Bearer`. For any other status the header is omitted unless passed
|
|
129
|
+
explicitly.
|
|
130
|
+
|
|
74
131
|
## Documentation
|
|
75
132
|
|
|
76
133
|
See the `docs/` folder for more detailed instructions and usage guides:
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Tools2Fast FastAPI
|
|
2
|
+
|
|
3
|
+
Shared tools, mixins, and base services for FastAPI applications. Designed for internal use by the Solautyc Team to standardize model definitions and common services across multiple packages.
|
|
4
|
+
|
|
5
|
+
> 📖 **Conventions reference**: this package follows the [2fast-handbook](https://github.com/AngelDanielSanchezCastillo/2fast-handbook) for ecosystem conventions (structure, versioning, README, commits, release).
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
You can install this package from PyPI (if published) or use it locally within your workspace:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install tools2fast-fastapi
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Locally with UV:
|
|
16
|
+
```bash
|
|
17
|
+
uv pip install -e path/to/tools2fast-fastapi
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- **SQLModel Mixins**: Standardized `IdMixin`, `TimestampMixin`, and `AuditMixin`.
|
|
23
|
+
- **Base Models**: Core models setup to be inherited across all entity definitions.
|
|
24
|
+
- **Unified API envelope**: Success and error helpers via `APIResponse`.
|
|
25
|
+
- **Auth error helper**: `APIResponse.auth_error(...)` returns a ready-to-return
|
|
26
|
+
`JSONResponse` with the project envelope and, for HTTP 401, the RFC 6750
|
|
27
|
+
`WWW-Authenticate` header.
|
|
28
|
+
- **Shared Services**: Reusable services logic for basic CRUD and related queries (coming soon).
|
|
29
|
+
|
|
30
|
+
## Auth error contract
|
|
31
|
+
|
|
32
|
+
`APIResponse.auth_error` produces a stable contract for authentication and
|
|
33
|
+
authorization failures. The discriminator is `error.type` (never the message),
|
|
34
|
+
which lets clients react without string matching:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from tools2fast_fastapi import APIResponse
|
|
38
|
+
|
|
39
|
+
return APIResponse.auth_error(
|
|
40
|
+
error_code="TokenExpired",
|
|
41
|
+
message="Token expirado",
|
|
42
|
+
status_code=401,
|
|
43
|
+
www_authenticate='Bearer error="expired_token"',
|
|
44
|
+
)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
When the failure happens inside a **FastAPI dependency**, return a `Response`
|
|
48
|
+
is not enough (FastAPI injects it as the dependency value instead of
|
|
49
|
+
short-circuiting). Raise `AuthError` and register the handler once at startup:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from fastapi import FastAPI
|
|
53
|
+
from tools2fast_fastapi import AuthError, install_auth_error_handler
|
|
54
|
+
|
|
55
|
+
app = FastAPI()
|
|
56
|
+
install_auth_error_handler(app)
|
|
57
|
+
|
|
58
|
+
async def get_current_user(...):
|
|
59
|
+
raise AuthError(
|
|
60
|
+
error_code="TokenExpired",
|
|
61
|
+
message="Token expirado",
|
|
62
|
+
www_authenticate='Bearer error="expired_token"',
|
|
63
|
+
)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Both paths produce the same envelope and the same RFC 6750 header.
|
|
67
|
+
|
|
68
|
+
| Situation | Status | `error.type` | `WWW-Authenticate` |
|
|
69
|
+
|---|---|---|---|
|
|
70
|
+
| Missing token | 401 | `TokenMissing` | `Bearer` |
|
|
71
|
+
| Malformed / bad signature | 401 | `TokenInvalid` | `Bearer error="invalid_token"` |
|
|
72
|
+
| Expired token | 401 | `TokenExpired` | `Bearer error="expired_token"` |
|
|
73
|
+
| Email not verified | 403 | `EmailNotVerified` | — |
|
|
74
|
+
| Missing permission | 403 | `PermissionDenied` | — |
|
|
75
|
+
| Missing role | 403 | `RoleMissing` | — |
|
|
76
|
+
| Valid token, no tenant | 403 | `TenantRequired` | — |
|
|
77
|
+
| Inactive tenant | 403 | `TenantInactive` | — |
|
|
78
|
+
|
|
79
|
+
When `status_code` is `401` and `www_authenticate` is omitted, the header
|
|
80
|
+
defaults to `Bearer`. For any other status the header is omitted unless passed
|
|
81
|
+
explicitly.
|
|
82
|
+
|
|
83
|
+
## Documentation
|
|
84
|
+
|
|
85
|
+
See the `docs/` folder for more detailed instructions and usage guides:
|
|
86
|
+
|
|
87
|
+
- [Usage Guide](docs/guide.md)
|
|
88
|
+
|
|
89
|
+
## Examples
|
|
90
|
+
|
|
91
|
+
Check the `examples/` folder for sample implementation.
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
This project is licensed under the MIT License.
|
|
@@ -2,6 +2,8 @@ from .models.mixins import AuditMixin, AuditTimestampMixin, IdMixin, TimestampMi
|
|
|
2
2
|
from .services import DocumentSimpleRevisionService, DocumentWithItemsRevisionService, TransactionService
|
|
3
3
|
from .schemas import (
|
|
4
4
|
APIResponse,
|
|
5
|
+
AuthError,
|
|
6
|
+
install_auth_error_handler,
|
|
5
7
|
BaseSuccessResponse,
|
|
6
8
|
BaseControlledErrorResponse,
|
|
7
9
|
BaseUnexpectedErrorResponse,
|
|
@@ -27,6 +29,8 @@ __all__ = [
|
|
|
27
29
|
"NumberMixin",
|
|
28
30
|
# Response models
|
|
29
31
|
"APIResponse",
|
|
32
|
+
"AuthError",
|
|
33
|
+
"install_auth_error_handler",
|
|
30
34
|
"BaseSuccessResponse",
|
|
31
35
|
"BaseControlledErrorResponse",
|
|
32
36
|
"BaseUnexpectedErrorResponse",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.3.14"
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/__init__.py
RENAMED
|
@@ -13,6 +13,8 @@ from .mixins import (
|
|
|
13
13
|
)
|
|
14
14
|
from .response_schema import (
|
|
15
15
|
APIResponse,
|
|
16
|
+
AuthError,
|
|
17
|
+
install_auth_error_handler,
|
|
16
18
|
BaseSuccessResponse,
|
|
17
19
|
BaseControlledErrorResponse,
|
|
18
20
|
BaseUnexpectedErrorResponse,
|
|
@@ -41,6 +43,8 @@ __all__ = [
|
|
|
41
43
|
"PaymentRequiredMixin",
|
|
42
44
|
# Response models
|
|
43
45
|
"APIResponse",
|
|
46
|
+
"AuthError",
|
|
47
|
+
"install_auth_error_handler",
|
|
44
48
|
"BaseSuccessResponse",
|
|
45
49
|
"BaseControlledErrorResponse",
|
|
46
50
|
"BaseUnexpectedErrorResponse",
|
|
@@ -15,20 +15,98 @@ Factoría:
|
|
|
15
15
|
from __future__ import annotations
|
|
16
16
|
|
|
17
17
|
import logging
|
|
18
|
-
from typing import Any, Generic, Literal, TypeVar
|
|
18
|
+
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar
|
|
19
19
|
|
|
20
|
+
from fastapi import HTTPException, status
|
|
21
|
+
from fastapi.responses import JSONResponse
|
|
20
22
|
from pydantic import BaseModel
|
|
21
|
-
from fastapi import status
|
|
22
23
|
|
|
23
24
|
from tools2fast_fastapi.schemas.mixins import (
|
|
24
25
|
ErrorDetail,
|
|
25
26
|
)
|
|
26
27
|
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from fastapi import FastAPI
|
|
30
|
+
|
|
27
31
|
logger = logging.getLogger(__name__)
|
|
28
32
|
|
|
29
33
|
T = TypeVar("T")
|
|
30
34
|
|
|
31
35
|
|
|
36
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
37
|
+
# AUTH ERROR — excepción para dependencies
|
|
38
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class AuthError(HTTPException):
|
|
42
|
+
"""Authentication/authorization failure raised from FastAPI dependencies.
|
|
43
|
+
|
|
44
|
+
Dependencies cannot return a ``Response`` to short-circuit the endpoint
|
|
45
|
+
(FastAPI injects it as the dependency value instead). Raising this
|
|
46
|
+
exception, together with :func:`install_auth_error_handler`, produces the
|
|
47
|
+
same envelope and RFC 6750 challenge as :meth:`APIResponse.auth_error`.
|
|
48
|
+
|
|
49
|
+
It subclasses :class:`fastapi.HTTPException` on purpose: if an application
|
|
50
|
+
forgets to install the handler, the status code and ``WWW-Authenticate``
|
|
51
|
+
header are still correct (the body falls back to FastAPI's ``detail``
|
|
52
|
+
shape instead of becoming a 500).
|
|
53
|
+
|
|
54
|
+
Attributes:
|
|
55
|
+
status_code: HTTP status (usually 401 or 403).
|
|
56
|
+
error_code: Stable discriminator stored in ``error.type``.
|
|
57
|
+
message: User-facing message (Spanish).
|
|
58
|
+
www_authenticate: Optional ``WWW-Authenticate`` value. Defaults to
|
|
59
|
+
``Bearer`` for 401 responses.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
*,
|
|
65
|
+
error_code: str,
|
|
66
|
+
message: str,
|
|
67
|
+
status_code: int = status.HTTP_401_UNAUTHORIZED,
|
|
68
|
+
www_authenticate: str | None = None,
|
|
69
|
+
) -> None:
|
|
70
|
+
headers: dict[str, str] = {}
|
|
71
|
+
if www_authenticate is not None or status_code == status.HTTP_401_UNAUTHORIZED:
|
|
72
|
+
headers["WWW-Authenticate"] = www_authenticate or "Bearer"
|
|
73
|
+
|
|
74
|
+
self.error_code = error_code
|
|
75
|
+
self.message = message
|
|
76
|
+
self.www_authenticate = www_authenticate
|
|
77
|
+
super().__init__(
|
|
78
|
+
status_code=status_code,
|
|
79
|
+
detail=message,
|
|
80
|
+
headers=headers or None,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def install_auth_error_handler(app: FastAPI) -> None:
|
|
85
|
+
"""Register the ``AuthError`` handler on a FastAPI application.
|
|
86
|
+
|
|
87
|
+
Call once during app startup, before serving requests:
|
|
88
|
+
|
|
89
|
+
.. code-block:: python
|
|
90
|
+
|
|
91
|
+
from tools2fast_fastapi import install_auth_error_handler
|
|
92
|
+
|
|
93
|
+
app = FastAPI()
|
|
94
|
+
install_auth_error_handler(app)
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
app: The FastAPI application instance.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
@app.exception_handler(AuthError)
|
|
101
|
+
async def _handle_auth_error(_request, exc: AuthError) -> JSONResponse:
|
|
102
|
+
return APIResponse.auth_error(
|
|
103
|
+
error_code=exc.error_code,
|
|
104
|
+
message=exc.message,
|
|
105
|
+
status_code=exc.status_code,
|
|
106
|
+
www_authenticate=exc.www_authenticate,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
32
110
|
# ═══════════════════════════════════════════════════════════════════════════════
|
|
33
111
|
# RESPUESTAS — Phase 1: Unified API Responses
|
|
34
112
|
# ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -266,6 +344,57 @@ class APIResponse:
|
|
|
266
344
|
error_detail = ErrorDetail(type="ControlledError", detail=message)
|
|
267
345
|
return BaseControlledErrorResponse(message=message, error=error_detail), status_code
|
|
268
346
|
|
|
347
|
+
@staticmethod
|
|
348
|
+
def auth_error(
|
|
349
|
+
*,
|
|
350
|
+
error_code: str,
|
|
351
|
+
message: str,
|
|
352
|
+
status_code: int = status.HTTP_401_UNAUTHORIZED,
|
|
353
|
+
www_authenticate: str | None = None,
|
|
354
|
+
) -> JSONResponse:
|
|
355
|
+
"""Error de autenticación/autorización listo para retornar.
|
|
356
|
+
|
|
357
|
+
Construye un :class:`~fastapi.responses.JSONResponse` con el envelope
|
|
358
|
+
del proyecto y, cuando aplica, el header RFC 6750
|
|
359
|
+
``WWW-Authenticate``.
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
error_code: Discriminador estable que viaja en ``error.type``
|
|
363
|
+
(por ejemplo ``"TokenExpired"``, ``"PermissionDenied"``).
|
|
364
|
+
El frontend discrimina por este valor, nunca por el mensaje.
|
|
365
|
+
message: Mensaje legible para el usuario (español).
|
|
366
|
+
status_code: Código HTTP. Por defecto ``401``.
|
|
367
|
+
www_authenticate: Valor del header ``WWW-Authenticate``. Si el
|
|
368
|
+
status es ``401`` y se omite, se usa ``"Bearer"``. Para
|
|
369
|
+
statuses distintos de ``401`` se omite salvo que se pase
|
|
370
|
+
explícitamente.
|
|
371
|
+
|
|
372
|
+
Returns:
|
|
373
|
+
``JSONResponse`` con el envelope del proyecto y los headers
|
|
374
|
+
correspondientes.
|
|
375
|
+
|
|
376
|
+
Example::
|
|
377
|
+
|
|
378
|
+
return APIResponse.auth_error(
|
|
379
|
+
error_code="TokenExpired",
|
|
380
|
+
message="Token expirado",
|
|
381
|
+
www_authenticate='Bearer error="expired_token"',
|
|
382
|
+
)
|
|
383
|
+
"""
|
|
384
|
+
error_detail = ErrorDetail(type=error_code, detail=message)
|
|
385
|
+
body = BaseControlledErrorResponse(message=message, error=error_detail)
|
|
386
|
+
|
|
387
|
+
headers: dict[str, str] = {}
|
|
388
|
+
is_unauthorized = status_code == status.HTTP_401_UNAUTHORIZED
|
|
389
|
+
if www_authenticate is not None or is_unauthorized:
|
|
390
|
+
headers["WWW-Authenticate"] = www_authenticate or "Bearer"
|
|
391
|
+
|
|
392
|
+
return JSONResponse(
|
|
393
|
+
status_code=status_code,
|
|
394
|
+
content=body.model_dump(),
|
|
395
|
+
headers=headers,
|
|
396
|
+
)
|
|
397
|
+
|
|
269
398
|
@staticmethod
|
|
270
399
|
def payment_required(
|
|
271
400
|
message: str = "Pago requerido",
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/skills/SKILL.md
RENAMED
|
@@ -4,7 +4,7 @@ description: "Trigger: working on or with tools2fast-fastapi. Shared base layer
|
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
author: AngelDanielSanchezCastillo
|
|
7
|
-
version: "1.
|
|
7
|
+
version: "1.2"
|
|
8
8
|
---
|
|
9
9
|
|
|
10
10
|
## Purpose
|
|
@@ -48,6 +48,14 @@ automation, and revision/document services. No settings module by design.
|
|
|
48
48
|
|
|
49
49
|
- Spanish response messages ("Éxito", "Guardado con éxito", "Ha ocurrido un error", "Pago requerido").
|
|
50
50
|
- All `error_type` values are Literals — only the three above exist.
|
|
51
|
+
- `APIResponse.auth_error(...)` (0.3.14+) returns a ready-to-return `JSONResponse`
|
|
52
|
+
with the project envelope and, for 401, the RFC 6750 `WWW-Authenticate` header.
|
|
53
|
+
It does NOT add a new `error_type`; the discriminator lives in `error.type`.
|
|
54
|
+
- Dependencies cannot short-circuit by returning a `Response` (FastAPI injects
|
|
55
|
+
it as the dependency value). Raise `AuthError(...)` and call
|
|
56
|
+
`install_auth_error_handler(app)` once at startup (0.3.14+) instead.
|
|
57
|
+
`AuthError` subclasses `HTTPException`, so a missing handler still yields the
|
|
58
|
+
correct status and challenge (only the body shape falls back to `detail`).
|
|
51
59
|
|
|
52
60
|
## Stale docs
|
|
53
61
|
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14/src/tools2fast_fastapi.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tools2fast-fastapi
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.14
|
|
4
4
|
Summary: Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use
|
|
5
5
|
Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -69,8 +69,65 @@ uv pip install -e path/to/tools2fast-fastapi
|
|
|
69
69
|
|
|
70
70
|
- **SQLModel Mixins**: Standardized `IdMixin`, `TimestampMixin`, and `AuditMixin`.
|
|
71
71
|
- **Base Models**: Core models setup to be inherited across all entity definitions.
|
|
72
|
+
- **Unified API envelope**: Success and error helpers via `APIResponse`.
|
|
73
|
+
- **Auth error helper**: `APIResponse.auth_error(...)` returns a ready-to-return
|
|
74
|
+
`JSONResponse` with the project envelope and, for HTTP 401, the RFC 6750
|
|
75
|
+
`WWW-Authenticate` header.
|
|
72
76
|
- **Shared Services**: Reusable services logic for basic CRUD and related queries (coming soon).
|
|
73
77
|
|
|
78
|
+
## Auth error contract
|
|
79
|
+
|
|
80
|
+
`APIResponse.auth_error` produces a stable contract for authentication and
|
|
81
|
+
authorization failures. The discriminator is `error.type` (never the message),
|
|
82
|
+
which lets clients react without string matching:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from tools2fast_fastapi import APIResponse
|
|
86
|
+
|
|
87
|
+
return APIResponse.auth_error(
|
|
88
|
+
error_code="TokenExpired",
|
|
89
|
+
message="Token expirado",
|
|
90
|
+
status_code=401,
|
|
91
|
+
www_authenticate='Bearer error="expired_token"',
|
|
92
|
+
)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
When the failure happens inside a **FastAPI dependency**, return a `Response`
|
|
96
|
+
is not enough (FastAPI injects it as the dependency value instead of
|
|
97
|
+
short-circuiting). Raise `AuthError` and register the handler once at startup:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from fastapi import FastAPI
|
|
101
|
+
from tools2fast_fastapi import AuthError, install_auth_error_handler
|
|
102
|
+
|
|
103
|
+
app = FastAPI()
|
|
104
|
+
install_auth_error_handler(app)
|
|
105
|
+
|
|
106
|
+
async def get_current_user(...):
|
|
107
|
+
raise AuthError(
|
|
108
|
+
error_code="TokenExpired",
|
|
109
|
+
message="Token expirado",
|
|
110
|
+
www_authenticate='Bearer error="expired_token"',
|
|
111
|
+
)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Both paths produce the same envelope and the same RFC 6750 header.
|
|
115
|
+
|
|
116
|
+
| Situation | Status | `error.type` | `WWW-Authenticate` |
|
|
117
|
+
|---|---|---|---|
|
|
118
|
+
| Missing token | 401 | `TokenMissing` | `Bearer` |
|
|
119
|
+
| Malformed / bad signature | 401 | `TokenInvalid` | `Bearer error="invalid_token"` |
|
|
120
|
+
| Expired token | 401 | `TokenExpired` | `Bearer error="expired_token"` |
|
|
121
|
+
| Email not verified | 403 | `EmailNotVerified` | — |
|
|
122
|
+
| Missing permission | 403 | `PermissionDenied` | — |
|
|
123
|
+
| Missing role | 403 | `RoleMissing` | — |
|
|
124
|
+
| Valid token, no tenant | 403 | `TenantRequired` | — |
|
|
125
|
+
| Inactive tenant | 403 | `TenantInactive` | — |
|
|
126
|
+
|
|
127
|
+
When `status_code` is `401` and `www_authenticate` is omitted, the header
|
|
128
|
+
defaults to `Bearer`. For any other status the header is omitted unless passed
|
|
129
|
+
explicitly.
|
|
130
|
+
|
|
74
131
|
## Documentation
|
|
75
132
|
|
|
76
133
|
See the `docs/` folder for more detailed instructions and usage guides:
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/SOURCES.txt
RENAMED
|
@@ -26,6 +26,7 @@ src/tools2fast_fastapi/services/transaction_service.py
|
|
|
26
26
|
src/tools2fast_fastapi/skills/SKILL.md
|
|
27
27
|
src/tools2fast_fastapi/utils/__init__.py
|
|
28
28
|
src/tools2fast_fastapi/utils/routing.py
|
|
29
|
+
tests/test_auth_error.py
|
|
29
30
|
tests/test_initial.py
|
|
30
31
|
tests/test_query_filters.py
|
|
31
32
|
tests/test_response_schema.py
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Tests for ``APIResponse.auth_error`` — standardized auth error responses.
|
|
3
|
+
|
|
4
|
+
The helper builds a ready-to-return ``JSONResponse`` carrying the project
|
|
5
|
+
envelope (``success=False, error_type="controlled", message, error``) and, for
|
|
6
|
+
401 responses, the RFC 6750 ``WWW-Authenticate`` header.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from fastapi.responses import JSONResponse
|
|
12
|
+
|
|
13
|
+
from tools2fast_fastapi.schemas.response_schema import APIResponse
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _payload(response: JSONResponse) -> dict:
|
|
17
|
+
"""Decode the JSON body of a JSONResponse."""
|
|
18
|
+
return json.loads(response.body.decode())
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TestAuthErrorDefaults:
|
|
22
|
+
"""Default behavior: 401 with a bare Bearer challenge."""
|
|
23
|
+
|
|
24
|
+
def test_returns_json_response(self):
|
|
25
|
+
"""RED: auth_error returns a JSONResponse instance."""
|
|
26
|
+
response = APIResponse.auth_error(
|
|
27
|
+
error_code="TokenExpired",
|
|
28
|
+
message="Token expirado",
|
|
29
|
+
)
|
|
30
|
+
assert isinstance(response, JSONResponse)
|
|
31
|
+
|
|
32
|
+
def test_default_status_is_401(self):
|
|
33
|
+
"""RED: default HTTP status must be 401."""
|
|
34
|
+
response = APIResponse.auth_error(
|
|
35
|
+
error_code="TokenExpired",
|
|
36
|
+
message="Token expirado",
|
|
37
|
+
)
|
|
38
|
+
assert response.status_code == 401
|
|
39
|
+
|
|
40
|
+
def test_default_www_authenticate_is_bearer(self):
|
|
41
|
+
"""RED: 401 without explicit challenge defaults to ``Bearer``."""
|
|
42
|
+
response = APIResponse.auth_error(
|
|
43
|
+
error_code="TokenMissing",
|
|
44
|
+
message="Token requerido",
|
|
45
|
+
)
|
|
46
|
+
assert response.headers.get("www-authenticate") == "Bearer"
|
|
47
|
+
|
|
48
|
+
def test_envelope_shape(self):
|
|
49
|
+
"""RED: body follows the project envelope with error.type as code."""
|
|
50
|
+
response = APIResponse.auth_error(
|
|
51
|
+
error_code="TokenInvalid",
|
|
52
|
+
message="Token inválido",
|
|
53
|
+
)
|
|
54
|
+
body = _payload(response)
|
|
55
|
+
assert body["success"] is False
|
|
56
|
+
assert body["error_type"] == "controlled"
|
|
57
|
+
assert body["message"] == "Token inválido"
|
|
58
|
+
assert body["error"]["type"] == "TokenInvalid"
|
|
59
|
+
assert body["error"]["detail"] == "Token inválido"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class TestAuthErrorChallenge:
|
|
63
|
+
"""Custom RFC 6750 challenge values."""
|
|
64
|
+
|
|
65
|
+
def test_custom_expired_token_challenge(self):
|
|
66
|
+
"""RED: explicit ``error="expired_token"`` challenge is preserved."""
|
|
67
|
+
response = APIResponse.auth_error(
|
|
68
|
+
error_code="TokenExpired",
|
|
69
|
+
message="Token expirado",
|
|
70
|
+
status_code=401,
|
|
71
|
+
www_authenticate='Bearer error="expired_token"',
|
|
72
|
+
)
|
|
73
|
+
assert (
|
|
74
|
+
response.headers.get("www-authenticate") == 'Bearer error="expired_token"'
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
def test_custom_invalid_token_challenge(self):
|
|
78
|
+
"""RED: explicit ``error="invalid_token"`` challenge is preserved."""
|
|
79
|
+
response = APIResponse.auth_error(
|
|
80
|
+
error_code="TokenInvalid",
|
|
81
|
+
message="Token inválido",
|
|
82
|
+
www_authenticate='Bearer error="invalid_token"',
|
|
83
|
+
)
|
|
84
|
+
assert (
|
|
85
|
+
response.headers.get("www-authenticate") == 'Bearer error="invalid_token"'
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class TestAuthErrorForbidden:
|
|
90
|
+
"""403 is authorization, not authentication: no Bearer challenge."""
|
|
91
|
+
|
|
92
|
+
def test_forbidden_status(self):
|
|
93
|
+
"""RED: 403 status is honored."""
|
|
94
|
+
response = APIResponse.auth_error(
|
|
95
|
+
error_code="PermissionDenied",
|
|
96
|
+
message="Permisos insuficientes",
|
|
97
|
+
status_code=403,
|
|
98
|
+
)
|
|
99
|
+
assert response.status_code == 403
|
|
100
|
+
|
|
101
|
+
def test_forbidden_has_no_www_authenticate(self):
|
|
102
|
+
"""RED: 403 must not advertise a Bearer challenge."""
|
|
103
|
+
response = APIResponse.auth_error(
|
|
104
|
+
error_code="PermissionDenied",
|
|
105
|
+
message="Permisos insuficientes",
|
|
106
|
+
status_code=403,
|
|
107
|
+
)
|
|
108
|
+
assert response.headers.get("www-authenticate") is None
|
|
109
|
+
|
|
110
|
+
def test_forbidden_envelope_shape(self):
|
|
111
|
+
"""RED: 403 keeps the same envelope and error code."""
|
|
112
|
+
response = APIResponse.auth_error(
|
|
113
|
+
error_code="TenantRequired",
|
|
114
|
+
message="Se requiere un tenant",
|
|
115
|
+
status_code=403,
|
|
116
|
+
)
|
|
117
|
+
body = _payload(response)
|
|
118
|
+
assert body["success"] is False
|
|
119
|
+
assert body["error"]["type"] == "TenantRequired"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
from fastapi import FastAPI
|
|
123
|
+
from fastapi.testclient import TestClient
|
|
124
|
+
|
|
125
|
+
from tools2fast_fastapi import AuthError, install_auth_error_handler
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class TestAuthErrorException:
|
|
129
|
+
"""AuthError is raised from dependencies to short-circuit the endpoint."""
|
|
130
|
+
|
|
131
|
+
def test_defaults(self):
|
|
132
|
+
"""RED: default status is 401 and no explicit challenge."""
|
|
133
|
+
exc = AuthError(error_code="TokenMissing", message="Credenciales requeridas")
|
|
134
|
+
assert exc.status_code == 401
|
|
135
|
+
assert exc.error_code == "TokenMissing"
|
|
136
|
+
assert exc.message == "Credenciales requeridas"
|
|
137
|
+
assert exc.www_authenticate is None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class TestInstallAuthErrorHandler:
|
|
141
|
+
"""The handler turns AuthError into the project envelope."""
|
|
142
|
+
|
|
143
|
+
def _app(self) -> FastAPI:
|
|
144
|
+
app = FastAPI()
|
|
145
|
+
install_auth_error_handler(app)
|
|
146
|
+
|
|
147
|
+
@app.get("/unauthorized")
|
|
148
|
+
async def unauthorized() -> None:
|
|
149
|
+
raise AuthError(
|
|
150
|
+
error_code="TokenExpired",
|
|
151
|
+
message="Token expirado",
|
|
152
|
+
www_authenticate='Bearer error="expired_token"',
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
@app.get("/forbidden")
|
|
156
|
+
async def forbidden() -> None:
|
|
157
|
+
raise AuthError(
|
|
158
|
+
error_code="PermissionDenied",
|
|
159
|
+
message="Permisos insuficientes",
|
|
160
|
+
status_code=403,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
return app
|
|
164
|
+
|
|
165
|
+
def test_401_envelope_and_challenge(self):
|
|
166
|
+
"""RED: AuthError becomes a 401 envelope with the challenge header."""
|
|
167
|
+
response = TestClient(self._app()).get("/unauthorized")
|
|
168
|
+
|
|
169
|
+
assert response.status_code == 401
|
|
170
|
+
body = response.json()
|
|
171
|
+
assert body["success"] is False
|
|
172
|
+
assert body["error"]["type"] == "TokenExpired"
|
|
173
|
+
assert (
|
|
174
|
+
response.headers.get("www-authenticate") == 'Bearer error="expired_token"'
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def test_403_envelope_without_challenge(self):
|
|
178
|
+
"""RED: AuthError becomes a 403 envelope without Bearer challenge."""
|
|
179
|
+
response = TestClient(self._app()).get("/forbidden")
|
|
180
|
+
|
|
181
|
+
assert response.status_code == 403
|
|
182
|
+
body = response.json()
|
|
183
|
+
assert body["error"]["type"] == "PermissionDenied"
|
|
184
|
+
assert response.headers.get("www-authenticate") is None
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
# Tools2Fast FastAPI
|
|
2
|
-
|
|
3
|
-
Shared tools, mixins, and base services for FastAPI applications. Designed for internal use by the Solautyc Team to standardize model definitions and common services across multiple packages.
|
|
4
|
-
|
|
5
|
-
> 📖 **Conventions reference**: this package follows the [2fast-handbook](https://github.com/AngelDanielSanchezCastillo/2fast-handbook) for ecosystem conventions (structure, versioning, README, commits, release).
|
|
6
|
-
|
|
7
|
-
## Installation
|
|
8
|
-
|
|
9
|
-
You can install this package from PyPI (if published) or use it locally within your workspace:
|
|
10
|
-
|
|
11
|
-
```bash
|
|
12
|
-
pip install tools2fast-fastapi
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
Locally with UV:
|
|
16
|
-
```bash
|
|
17
|
-
uv pip install -e path/to/tools2fast-fastapi
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
## Features
|
|
21
|
-
|
|
22
|
-
- **SQLModel Mixins**: Standardized `IdMixin`, `TimestampMixin`, and `AuditMixin`.
|
|
23
|
-
- **Base Models**: Core models setup to be inherited across all entity definitions.
|
|
24
|
-
- **Shared Services**: Reusable services logic for basic CRUD and related queries (coming soon).
|
|
25
|
-
|
|
26
|
-
## Documentation
|
|
27
|
-
|
|
28
|
-
See the `docs/` folder for more detailed instructions and usage guides:
|
|
29
|
-
|
|
30
|
-
- [Usage Guide](docs/guide.md)
|
|
31
|
-
|
|
32
|
-
## Examples
|
|
33
|
-
|
|
34
|
-
Check the `examples/` folder for sample implementation.
|
|
35
|
-
|
|
36
|
-
## License
|
|
37
|
-
|
|
38
|
-
This project is licensed under the MIT License.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.3.13"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/models/__init__.py
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/models/mixins.py
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/mixins.py
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/utils/__init__.py
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/utils/routing.py
RENAMED
|
File without changes
|
|
File without changes
|
{tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/requires.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|