tools2fast-fastapi 0.3.13__tar.gz → 0.4.0__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.
Files changed (40) hide show
  1. {tools2fast_fastapi-0.3.13/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.4.0}/PKG-INFO +61 -5
  2. tools2fast_fastapi-0.4.0/README.md +95 -0
  3. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/pyproject.toml +3 -4
  4. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/__init__.py +13 -1
  5. tools2fast_fastapi-0.4.0/src/tools2fast_fastapi/__version__.py +1 -0
  6. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/models/mixins.py +59 -5
  7. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/schemas/__init__.py +4 -0
  8. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/schemas/mixins.py +24 -3
  9. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/schemas/response_schema.py +131 -2
  10. tools2fast_fastapi-0.4.0/src/tools2fast_fastapi/services/soft_delete.py +148 -0
  11. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/skills/SKILL.md +9 -1
  12. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0/src/tools2fast_fastapi.egg-info}/PKG-INFO +61 -5
  13. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi.egg-info/SOURCES.txt +4 -1
  14. tools2fast_fastapi-0.4.0/tests/test_auth_error.py +184 -0
  15. tools2fast_fastapi-0.4.0/tests/test_uuid_soft_delete_mixins.py +226 -0
  16. tools2fast_fastapi-0.3.13/README.md +0 -38
  17. tools2fast_fastapi-0.3.13/src/tools2fast_fastapi/__version__.py +0 -1
  18. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/LICENSE +0 -0
  19. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/MANIFEST.in +0 -0
  20. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/docs/guide.md +0 -0
  21. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/examples/example.py +0 -0
  22. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/setup.cfg +0 -0
  23. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/models/__init__.py +0 -0
  24. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/services/__init__.py +0 -0
  25. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/services/document_simple_revision_service.py +0 -0
  26. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/services/document_with_items_revision_service.py +0 -0
  27. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/services/number_service.py +0 -0
  28. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/services/query_filters.py +0 -0
  29. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/services/revision_service.py +0 -0
  30. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/services/transaction_service.py +0 -0
  31. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/utils/__init__.py +0 -0
  32. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi/utils/routing.py +0 -0
  33. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
  34. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
  35. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
  36. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/tests/test_initial.py +0 -0
  37. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/tests/test_query_filters.py +0 -0
  38. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/tests/test_response_schema.py +0 -0
  39. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/tests/test_revision_service.py +0 -0
  40. {tools2fast_fastapi-0.3.13 → tools2fast_fastapi-0.4.0}/tests/test_schemas.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tools2fast-fastapi
3
- Version: 0.3.13
3
+ Version: 0.4.0
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
@@ -34,12 +34,11 @@ Classifier: Development Status :: 3 - Alpha
34
34
  Classifier: Intended Audience :: Developers
35
35
  Classifier: License :: OSI Approved :: MIT License
36
36
  Classifier: Programming Language :: Python :: 3
37
- Classifier: Programming Language :: Python :: 3.10
38
- Classifier: Programming Language :: Python :: 3.11
39
- Classifier: Programming Language :: Python :: 3.12
37
+ Classifier: Programming Language :: Python :: 3.14
38
+ Classifier: Programming Language :: Python :: 3.15
40
39
  Classifier: Framework :: FastAPI
41
40
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
42
- Requires-Python: >=3.10
41
+ Requires-Python: >=3.14
43
42
  Description-Content-Type: text/markdown
44
43
  License-File: LICENSE
45
44
  Requires-Dist: fastapi>=0.100.0
@@ -69,8 +68,65 @@ uv pip install -e path/to/tools2fast-fastapi
69
68
 
70
69
  - **SQLModel Mixins**: Standardized `IdMixin`, `TimestampMixin`, and `AuditMixin`.
71
70
  - **Base Models**: Core models setup to be inherited across all entity definitions.
71
+ - **Unified API envelope**: Success and error helpers via `APIResponse`.
72
+ - **Auth error helper**: `APIResponse.auth_error(...)` returns a ready-to-return
73
+ `JSONResponse` with the project envelope and, for HTTP 401, the RFC 6750
74
+ `WWW-Authenticate` header.
72
75
  - **Shared Services**: Reusable services logic for basic CRUD and related queries (coming soon).
73
76
 
77
+ ## Auth error contract
78
+
79
+ `APIResponse.auth_error` produces a stable contract for authentication and
80
+ authorization failures. The discriminator is `error.type` (never the message),
81
+ which lets clients react without string matching:
82
+
83
+ ```python
84
+ from tools2fast_fastapi import APIResponse
85
+
86
+ return APIResponse.auth_error(
87
+ error_code="TokenExpired",
88
+ message="Token expirado",
89
+ status_code=401,
90
+ www_authenticate='Bearer error="expired_token"',
91
+ )
92
+ ```
93
+
94
+ When the failure happens inside a **FastAPI dependency**, return a `Response`
95
+ is not enough (FastAPI injects it as the dependency value instead of
96
+ short-circuiting). Raise `AuthError` and register the handler once at startup:
97
+
98
+ ```python
99
+ from fastapi import FastAPI
100
+ from tools2fast_fastapi import AuthError, install_auth_error_handler
101
+
102
+ app = FastAPI()
103
+ install_auth_error_handler(app)
104
+
105
+ async def get_current_user(...):
106
+ raise AuthError(
107
+ error_code="TokenExpired",
108
+ message="Token expirado",
109
+ www_authenticate='Bearer error="expired_token"',
110
+ )
111
+ ```
112
+
113
+ Both paths produce the same envelope and the same RFC 6750 header.
114
+
115
+ | Situation | Status | `error.type` | `WWW-Authenticate` |
116
+ |---|---|---|---|
117
+ | Missing token | 401 | `TokenMissing` | `Bearer` |
118
+ | Malformed / bad signature | 401 | `TokenInvalid` | `Bearer error="invalid_token"` |
119
+ | Expired token | 401 | `TokenExpired` | `Bearer error="expired_token"` |
120
+ | Email not verified | 403 | `EmailNotVerified` | — |
121
+ | Missing permission | 403 | `PermissionDenied` | — |
122
+ | Missing role | 403 | `RoleMissing` | — |
123
+ | Valid token, no tenant | 403 | `TenantRequired` | — |
124
+ | Inactive tenant | 403 | `TenantInactive` | — |
125
+
126
+ When `status_code` is `401` and `www_authenticate` is omitted, the header
127
+ defaults to `Bearer`. For any other status the header is omitted unless passed
128
+ explicitly.
129
+
74
130
  ## Documentation
75
131
 
76
132
  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.
@@ -7,7 +7,7 @@ name = "tools2fast-fastapi"
7
7
  dynamic = ["version"]
8
8
  description = "Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use"
9
9
  readme = "README.md"
10
- requires-python = ">=3.10"
10
+ requires-python = ">=3.14"
11
11
  license = {file = "LICENSE"}
12
12
  authors = [
13
13
  {name = "Angel Daniel Sanchez Castillo", email = "angeldaniel.sanchezcastillo@gmail.com"}
@@ -18,9 +18,8 @@ classifiers = [
18
18
  "Intended Audience :: Developers",
19
19
  "License :: OSI Approved :: MIT License",
20
20
  "Programming Language :: Python :: 3",
21
- "Programming Language :: Python :: 3.10",
22
- "Programming Language :: Python :: 3.11",
23
- "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Programming Language :: Python :: 3.15",
24
23
  "Framework :: FastAPI",
25
24
  "Topic :: Software Development :: Libraries :: Python Modules",
26
25
  ]
@@ -1,7 +1,10 @@
1
- from .models.mixins import AuditMixin, AuditTimestampMixin, IdMixin, TimestampMixin, NumberUniqueMixin, RevisionMixin, NumberMixin
1
+ from .models.mixins import AuditMixin, AuditTimestampMixin, IdMixin, UUIDIdMixin, TimestampMixin, NumberUniqueMixin, RevisionMixin, NumberMixin, SoftDeleteMixin
2
2
  from .services import DocumentSimpleRevisionService, DocumentWithItemsRevisionService, TransactionService
3
+ from .services.soft_delete import soft_delete, restore, active_only, deleted_only
3
4
  from .schemas import (
4
5
  APIResponse,
6
+ AuthError,
7
+ install_auth_error_handler,
5
8
  BaseSuccessResponse,
6
9
  BaseControlledErrorResponse,
7
10
  BaseUnexpectedErrorResponse,
@@ -20,13 +23,22 @@ __all__ = [
20
23
  # Model mixins
21
24
  "AuditTimestampMixin",
22
25
  "IdMixin",
26
+ "UUIDIdMixin",
23
27
  "TimestampMixin",
24
28
  "AuditMixin",
25
29
  "NumberUniqueMixin",
26
30
  "RevisionMixin",
27
31
  "NumberMixin",
32
+ "SoftDeleteMixin",
33
+ # Soft-delete functions
34
+ "soft_delete",
35
+ "restore",
36
+ "active_only",
37
+ "deleted_only",
28
38
  # Response models
29
39
  "APIResponse",
40
+ "AuthError",
41
+ "install_auth_error_handler",
30
42
  "BaseSuccessResponse",
31
43
  "BaseControlledErrorResponse",
32
44
  "BaseUnexpectedErrorResponse",
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"
@@ -1,15 +1,40 @@
1
1
  from datetime import datetime, timezone
2
+ from uuid import UUID, uuid7
2
3
 
3
4
  from sqlalchemy import DateTime, func, event
4
5
  from sqlmodel import BigInteger, Field
5
6
 
6
7
 
7
8
  class IdMixin:
8
- """Mixin para proveer clave primaria autoincremental tipo BigInteger."""
9
+ """
10
+ DEPRECATED: Use UUIDIdMixin instead.
11
+
12
+ Mixin para proveer clave primaria autoincremental tipo BigInteger.
13
+
14
+ .. deprecated:: 0.4.0
15
+ Use :class:`UUIDIdMixin` for new models. IdMixin will be removed in a future version.
16
+ """
17
+
18
+ def __init_subclass__(cls, **kwargs):
19
+ """Emit deprecation warning when subclassed."""
20
+ import warnings
21
+ warnings.warn(
22
+ "IdMixin is deprecated and will be removed in a future version. "
23
+ "Use UUIDIdMixin instead for UUID v7 primary keys.",
24
+ DeprecationWarning,
25
+ stacklevel=2,
26
+ )
27
+ super().__init_subclass__(**kwargs)
9
28
 
10
29
  id: int | None = Field(default=None, primary_key=True, index=True, sa_type=BigInteger)
11
30
 
12
31
 
32
+ class UUIDIdMixin:
33
+ """Mixin para proveer clave primaria tipo UUID v7 (time-ordered)."""
34
+
35
+ id: UUID = Field(default_factory=uuid7, primary_key=True, index=True)
36
+
37
+
13
38
  class TimestampMixin:
14
39
  """Mixin reutilizable para marcas de tiempo en UTC."""
15
40
 
@@ -29,19 +54,48 @@ class TimestampMixin:
29
54
  class AuditMixin:
30
55
  """Mixin para rastrear el usuario que crea y actualiza un registro."""
31
56
 
32
- created_by: int | None = Field(
57
+ created_by: UUID | None = Field(
33
58
  default=None,
34
59
  index=True,
35
60
  description="ID of the user who created this record.",
36
- sa_type=BigInteger,
37
61
  )
38
- updated_by: int | None = Field(
62
+ updated_by: UUID | None = Field(
39
63
  default=None,
40
64
  index=True,
41
65
  description="ID of the user who last updated this record.",
42
- sa_type=BigInteger,
43
66
  )
44
67
 
68
+
69
+ class SoftDeleteMixin:
70
+ """
71
+ Mixin para borrado lógico (soft delete).
72
+
73
+ Agrega:
74
+ - deleted_at (datetime | None): Timestamp de cuándo se borró el registro.
75
+ - deleted_by (UUID | None): ID del usuario que borró el registro.
76
+
77
+ Uso:
78
+ class MyModel(UUIDIdMixin, TimestampMixin, SoftDeleteMixin, SQLModel, table=True):
79
+ __tablename__ = "my_models"
80
+ name: str = Field()
81
+
82
+ El registro se considera "borrado" cuando deleted_at no es None.
83
+ Para filtrar registros activos, usar active_only(query).
84
+ Para filtrar registros borrados, usar deleted_only(query).
85
+ """
86
+
87
+ deleted_at: datetime | None = Field(
88
+ default=None,
89
+ index=True,
90
+ description="Timestamp when the record was soft-deleted. None means active.",
91
+ sa_type=DateTime(timezone=True),
92
+ )
93
+ deleted_by: UUID | None = Field(
94
+ default=None,
95
+ description="ID of the user who soft-deleted this record.",
96
+ )
97
+
98
+
45
99
  class NumberMixin:
46
100
  """
47
101
  Mixin para proveer un campo `number` que actúa como un identificador continuo
@@ -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",
@@ -1,5 +1,6 @@
1
1
  from datetime import datetime
2
2
  from typing import Literal
3
+ from uuid import UUID
3
4
 
4
5
  from pydantic import BaseModel
5
6
  from sqlmodel import SQLModel
@@ -98,11 +99,24 @@ class PaymentRequiredMixin(BaseModel):
98
99
 
99
100
 
100
101
  class IdMixin(SQLModel):
101
- """Schema mixin para recursos que tienen un ID entero."""
102
+ """
103
+ DEPRECATED: Use UUIDIdMixin instead.
104
+
105
+ Schema mixin para recursos que tienen un ID entero.
106
+
107
+ .. deprecated:: 0.4.0
108
+ Use :class:`UUIDIdMixin` for new schemas. IdMixin will be removed in a future version.
109
+ """
102
110
 
103
111
  id: int
104
112
 
105
113
 
114
+ class UUIDIdMixin(SQLModel):
115
+ """Schema mixin para recursos que tienen un ID UUID."""
116
+
117
+ id: UUID
118
+
119
+
106
120
  class TimestampMixin(SQLModel):
107
121
  """Schema mixin para recursos que incluyen timestamps de creación y actualización."""
108
122
 
@@ -113,8 +127,15 @@ class TimestampMixin(SQLModel):
113
127
  class AuditMixin(SQLModel):
114
128
  """Schema mixin para recursos que incluyen IDs de usuario auditables."""
115
129
 
116
- created_by: int | None = None
117
- updated_by: int | None = None
130
+ created_by: UUID | None = None
131
+ updated_by: UUID | None = None
132
+
133
+
134
+ class SoftDeleteMixin(SQLModel):
135
+ """Schema mixin para recursos que incluyen campos de borrado lógico."""
136
+
137
+ deleted_at: datetime | None = None
138
+ deleted_by: UUID | None = None
118
139
 
119
140
 
120
141
  class NumberMixin(SQLModel):
@@ -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",