tools2fast-fastapi 0.3.12__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.12 → tools2fast_fastapi-0.3.14}/MANIFEST.in +3 -2
- {tools2fast_fastapi-0.3.12/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.12 → 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.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/__init__.py +4 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/response_schema.py +131 -2
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/__init__.py +4 -0
- tools2fast_fastapi-0.3.14/src/tools2fast_fastapi/services/query_filters.py +122 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/skills/SKILL.md +9 -1
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14/src/tools2fast_fastapi.egg-info}/PKG-INFO +58 -1
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/SOURCES.txt +3 -0
- tools2fast_fastapi-0.3.14/tests/test_auth_error.py +184 -0
- tools2fast_fastapi-0.3.14/tests/test_query_filters.py +390 -0
- tools2fast_fastapi-0.3.12/README.md +0 -38
- tools2fast_fastapi-0.3.12/src/tools2fast_fastapi/__version__.py +0 -1
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/LICENSE +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/docs/guide.md +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/examples/example.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/pyproject.toml +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/setup.cfg +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/models/__init__.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/models/mixins.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/schemas/mixins.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/document_simple_revision_service.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/document_with_items_revision_service.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/number_service.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/revision_service.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/transaction_service.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/utils/__init__.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/utils/routing.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/tests/test_initial.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/tests/test_response_schema.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/tests/test_revision_service.py +0 -0
- {tools2fast_fastapi-0.3.12 → tools2fast_fastapi-0.3.14}/tests/test_schemas.py +0 -0
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
include README.md
|
|
2
2
|
include LICENSE
|
|
3
3
|
recursive-include docs *.md *.example
|
|
4
|
-
recursive-include examples *.py
|
|
5
|
-
recursive-include src/tools2fast_fastapi *.py *.html
|
|
4
|
+
recursive-include examples *.py *.example *.json
|
|
5
|
+
recursive-include src/tools2fast_fastapi *.py *.html *.json *.md
|
|
6
|
+
|
|
6
7
|
global-exclude __pycache__
|
|
7
8
|
global-exclude *.py[co]
|
|
8
9
|
global-exclude .DS_Store
|
{tools2fast_fastapi-0.3.12/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.12 → 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.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi/services/__init__.py
RENAMED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from .document_simple_revision_service import DocumentSimpleRevisionService
|
|
2
2
|
from .document_with_items_revision_service import DocumentWithItemsRevisionService
|
|
3
3
|
from .number_service import get_next_number
|
|
4
|
+
from .query_filters import apply_filters, build_count, list_with_total
|
|
4
5
|
from .revision_service import get_latest_revision, list_revisions, create_revision, clone_children
|
|
5
6
|
from .transaction_service import TransactionService
|
|
6
7
|
|
|
@@ -9,6 +10,9 @@ __all__ = [
|
|
|
9
10
|
"DocumentSimpleRevisionService",
|
|
10
11
|
"DocumentWithItemsRevisionService",
|
|
11
12
|
"get_next_number",
|
|
13
|
+
"apply_filters",
|
|
14
|
+
"build_count",
|
|
15
|
+
"list_with_total",
|
|
12
16
|
"get_latest_revision",
|
|
13
17
|
"list_revisions",
|
|
14
18
|
"create_revision",
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Filtros de consulta genericos reutilizables para listados paginados.
|
|
2
|
+
|
|
3
|
+
Provee un mini-DSL de filtros (igualdad exacta + sufijos), un constructor de
|
|
4
|
+
COUNT que reutiliza los WHERE filtrados y un helper que ejecuta las dos
|
|
5
|
+
consultas (total + items paginados) en una sola llamada.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any, TypeVar, cast
|
|
9
|
+
|
|
10
|
+
from fastapi import HTTPException
|
|
11
|
+
from sqlalchemy import Select, func
|
|
12
|
+
from sqlalchemy.engine import Row
|
|
13
|
+
from sqlalchemy.sql.elements import ColumnElement
|
|
14
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
15
|
+
|
|
16
|
+
ModelT = TypeVar("ModelT", bound=Any)
|
|
17
|
+
|
|
18
|
+
# Sufijos soportados por el DSL: <campo>__<sufijo>
|
|
19
|
+
_FILTER_SUFFIXES = ("__contains", "__in", "__gte", "__lte")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _split_suffix(key: str) -> tuple[str, str]:
|
|
23
|
+
"""Separa el campo del sufijo DSL (ej. 'code__contains' -> ('code', '__contains'))."""
|
|
24
|
+
for suffix in _FILTER_SUFFIXES:
|
|
25
|
+
if key.endswith(suffix) and len(key) > len(suffix):
|
|
26
|
+
return key[: -len(suffix)], suffix
|
|
27
|
+
return key, ""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def apply_filters(stmt: Select, model: type[ModelT], filters: dict) -> Select:
|
|
31
|
+
"""Aplica filtros con whitelist sobre el statement.
|
|
32
|
+
|
|
33
|
+
Nombres planos = igualdad exacta (incluye booleanos y FKs). Sufijos:
|
|
34
|
+
- ``__contains``: contiene el texto (LIKE %valor%).
|
|
35
|
+
- ``__in``: pertenece a una lista de valores.
|
|
36
|
+
- ``__gte`` / ``__lte``: mayor/igual o menor/igual.
|
|
37
|
+
Los valores llegan tipados por FastAPI (no se coercionan aqui). Un campo
|
|
38
|
+
fuera de la whitelist del modelo lanza HTTPException 422 en espanol.
|
|
39
|
+
"""
|
|
40
|
+
whitelist = {column.name for column in cast(Any, model).__table__.columns}
|
|
41
|
+
for key, value in filters.items():
|
|
42
|
+
# Parametros opcionales no enviados (None) se ignoran
|
|
43
|
+
if value is None:
|
|
44
|
+
continue
|
|
45
|
+
field, suffix = _split_suffix(key)
|
|
46
|
+
if field not in whitelist:
|
|
47
|
+
raise HTTPException(
|
|
48
|
+
status_code=422,
|
|
49
|
+
detail=(
|
|
50
|
+
f"Campo de filtro '{field}' no permitido para "
|
|
51
|
+
f"el modelo {model.__name__}."
|
|
52
|
+
),
|
|
53
|
+
)
|
|
54
|
+
column = getattr(model, field)
|
|
55
|
+
column = cast(Any, column)
|
|
56
|
+
if suffix == "__contains":
|
|
57
|
+
stmt = stmt.where(column.contains(str(value)))
|
|
58
|
+
elif suffix == "__in":
|
|
59
|
+
stmt = stmt.where(column.in_(value))
|
|
60
|
+
elif suffix == "__gte":
|
|
61
|
+
stmt = stmt.where(column >= value)
|
|
62
|
+
elif suffix == "__lte":
|
|
63
|
+
stmt = stmt.where(column <= value)
|
|
64
|
+
else:
|
|
65
|
+
stmt = stmt.where(column == value)
|
|
66
|
+
return stmt
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def build_count(stmt: Select, model: type[ModelT]) -> Select:
|
|
70
|
+
"""Construye un ``select(func.count(model.id))`` con los WHERE filtrados.
|
|
71
|
+
|
|
72
|
+
Reutiliza las condiciones WHERE y los FROM/JOIN del statement (necesario
|
|
73
|
+
para statements base pre-construidos como el de latest-revision de
|
|
74
|
+
cotizaciones) pero excluye offset/limit, order_by y group_by: el total
|
|
75
|
+
siempre refleja el universo filtrado, no la pagina.
|
|
76
|
+
"""
|
|
77
|
+
inner = stmt.order_by(None).group_by(None).offset(None).limit(None)
|
|
78
|
+
return inner.with_only_columns(func.count(cast(Any, model).id))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _scalar_count(result: Any) -> int:
|
|
82
|
+
"""Normaliza el valor del COUNT sin importar el tipo de statement.
|
|
83
|
+
|
|
84
|
+
``session.exec`` devuelve un escalar puro cuando el statement es un
|
|
85
|
+
``SelectOfScalar`` (sqlmodel.select) y un ``Row`` cuando es un ``Select``
|
|
86
|
+
plano de SQLAlchemy. Ambos representan el mismo valor.
|
|
87
|
+
"""
|
|
88
|
+
first = result.one()
|
|
89
|
+
if isinstance(first, Row):
|
|
90
|
+
return int(first[0])
|
|
91
|
+
return int(first)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def list_with_total(
|
|
95
|
+
session: AsyncSession,
|
|
96
|
+
stmt: Select,
|
|
97
|
+
model: type[ModelT],
|
|
98
|
+
filters: dict,
|
|
99
|
+
skip: int = 0,
|
|
100
|
+
limit: int = 50,
|
|
101
|
+
order_by: ColumnElement | None = None,
|
|
102
|
+
) -> tuple[list, int]:
|
|
103
|
+
"""Ejecuta las dos consultas de un listado paginado: total + items.
|
|
104
|
+
|
|
105
|
+
- ``count``: sin paginacion, reutilizando los mismos filtros (build_count).
|
|
106
|
+
- ``items``: con offset/limit y un order_by opcional.
|
|
107
|
+
|
|
108
|
+
Acepta un statement base pre-construido (p. ej. el de latest-revision de
|
|
109
|
+
cotizaciones) al que se le aplican los filtros encima. Devuelve
|
|
110
|
+
``(items, total)`` donde total es el universo filtrado completo.
|
|
111
|
+
"""
|
|
112
|
+
filtered = apply_filters(stmt, model, filters)
|
|
113
|
+
count_stmt = build_count(filtered, model)
|
|
114
|
+
|
|
115
|
+
total = _scalar_count(await session.exec(count_stmt))
|
|
116
|
+
|
|
117
|
+
items_stmt = filtered.offset(skip).limit(limit)
|
|
118
|
+
if order_by is not None:
|
|
119
|
+
items_stmt = items_stmt.order_by(order_by)
|
|
120
|
+
|
|
121
|
+
result = await session.exec(items_stmt)
|
|
122
|
+
return list(result.all()), total
|
{tools2fast_fastapi-0.3.12 → 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.12 → 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.12 → tools2fast_fastapi-0.3.14}/src/tools2fast_fastapi.egg-info/SOURCES.txt
RENAMED
|
@@ -20,12 +20,15 @@ src/tools2fast_fastapi/services/__init__.py
|
|
|
20
20
|
src/tools2fast_fastapi/services/document_simple_revision_service.py
|
|
21
21
|
src/tools2fast_fastapi/services/document_with_items_revision_service.py
|
|
22
22
|
src/tools2fast_fastapi/services/number_service.py
|
|
23
|
+
src/tools2fast_fastapi/services/query_filters.py
|
|
23
24
|
src/tools2fast_fastapi/services/revision_service.py
|
|
24
25
|
src/tools2fast_fastapi/services/transaction_service.py
|
|
25
26
|
src/tools2fast_fastapi/skills/SKILL.md
|
|
26
27
|
src/tools2fast_fastapi/utils/__init__.py
|
|
27
28
|
src/tools2fast_fastapi/utils/routing.py
|
|
29
|
+
tests/test_auth_error.py
|
|
28
30
|
tests/test_initial.py
|
|
31
|
+
tests/test_query_filters.py
|
|
29
32
|
tests/test_response_schema.py
|
|
30
33
|
tests/test_revision_service.py
|
|
31
34
|
tests/test_schemas.py
|