feat: Implement multi-tenancy support in middleware and security layers

- Enhanced TenantMiddleware to validate tenant information from JWT tokens.
- Added LicenseValidationMiddleware to check tenant licenses before processing requests.
- Updated security utilities to extract tenant information from tokens and validate company access.
- Introduced CompanyStore to manage active company state and handle company switching in the frontend.
- Modified API routes to include company_id in requests for better resource management.
- Improved logging and error handling throughout the middleware and API layers.
- Updated frontend components to reflect changes in company management and selection.
- Added new API route for fetching user's companies with proper authentication handling.
This commit is contained in:
2025-11-11 14:00:56 -06:00
parent e1eb6bbd01
commit 52b8fcd434
242 changed files with 7067 additions and 3274 deletions

View File

@@ -1,9 +1,9 @@
from pydantic import BaseModel, Field
from pydantic import ConfigDict
class ValuationMethodDTO(BaseModel):
key: str = Field(..., min_length=1, max_length=2)
description: str
model_config = ConfigDict(from_attributes=True)

View File

@@ -2,14 +2,15 @@ from sqlalchemy import String, PrimaryKeyConstraint
from sqlalchemy.orm import mapped_column, Mapped
from core.database import Base
class ValuationMethod(Base):
__tablename__ = "valuation_methods" #GMetValor
__tablename__ = "valuation_methods" # GMetValor
__table_args__ = (
PrimaryKeyConstraint("key", name="valuation_methods_pkey"),
{"schema": "public"}
{"schema": "public"},
)
key: Mapped[str] = mapped_column(String(2), nullable=False)
key: Mapped[str] = mapped_column(String(2), nullable=False)
description: Mapped[str] = mapped_column(String(200), nullable=False)
def __repr__(self):

View File

@@ -1,4 +1,3 @@
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from core.database import get_core_db
@@ -11,13 +10,12 @@ from typing import Any, Dict
router = APIRouter(prefix="/valuation-methods")
@router.get("/", response_model=Dict[str, Any])
async def list_valuation_methods(
page: int = Query(1, ge=1, description="Número de página"),
page_size: int = Query(50, ge=1, le=100, description="Tamaño de página"),
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user)
current_user: dict = Depends(get_current_user),
):
skip = (page - 1) * page_size
query = db.query(ValuationMethod)
@@ -27,23 +25,27 @@ async def list_valuation_methods(
"items": [ValuationMethodDTO.model_validate(obj) for obj in items],
"total": total,
"page": page,
"page_size": page_size
"page_size": page_size,
}
@router.get("/{key}", response_model=ValuationMethodDTO)
async def get_valuation_method(key: str, db: Session = Depends(get_core_db), current_user: dict = Depends(get_current_user)):
async def get_valuation_method(
key: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
obj = db.query(ValuationMethod).filter(ValuationMethod.key == key).first()
if not obj:
raise HTTPException(status_code=404, detail="Not found")
return obj
@router.post("/", response_model=ValuationMethodDTO, status_code=201)
async def create_valuation_method(
data: ValuationMethodDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(has_role("admin"))
current_user: dict = Depends(has_role("admin")),
):
obj = ValuationMethod(**data.dict())
db.add(obj)
@@ -51,13 +53,13 @@ async def create_valuation_method(
db.refresh(obj)
return obj
@router.put("/{key}", response_model=ValuationMethodDTO)
async def update_valuation_method(
key: str,
data: ValuationMethodDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(has_role("admin"))
current_user: dict = Depends(has_role("admin")),
):
obj = db.query(ValuationMethod).filter(ValuationMethod.key == key).first()
if not obj:
@@ -68,12 +70,12 @@ async def update_valuation_method(
db.refresh(obj)
return obj
@router.delete("/{key}", status_code=204)
async def delete_valuation_method(
key: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(has_role("admin"))
current_user: dict = Depends(has_role("admin")),
):
obj = db.query(ValuationMethod).filter(ValuationMethod.key == key).first()
if not obj:

View File

@@ -6,4 +6,4 @@ seed = [
("4", "VALOR DE PRECIO UNITARIO DE VENTA."),
("5", "VALOR RECONSTRUIDO."),
("6", "ULTIMO RECURSO"),
]
]

View File

@@ -7,6 +7,7 @@ app = FastAPI()
app.include_router(router)
client = TestClient(app)
@pytest.mark.usefixtures("client", "access_token")
def test_list_valuation_methods(client, access_token):
headers = {"Authorization": f"Bearer {access_token}"}
@@ -16,20 +17,28 @@ def test_list_valuation_methods(client, access_token):
assert "page" in response.json()
assert "page_size" in response.json()
@pytest.mark.usefixtures("client", "access_token")
def test_get_valuation_method_not_found(client, access_token):
headers = {"Authorization": f"Bearer {access_token}"}
response = client.get("/valuation-methods/invalid_key", headers=headers)
assert response.status_code == 404
def test_create_valuation_method_forbidden():
response = client.post("/valuation-methods/", json={"key": "TST", "description": "Test"})
response = client.post(
"/valuation-methods/", json={"key": "TST", "description": "Test"}
)
assert response.status_code in (403, 405, 404)
def test_update_valuation_method_forbidden():
response = client.put("/valuation-methods/TST", json={"key": "TST", "description": "Test"})
response = client.put(
"/valuation-methods/TST", json={"key": "TST", "description": "Test"}
)
assert response.status_code in (403, 405, 404)
def test_delete_valuation_method_forbidden():
response = client.delete("/valuation-methods/TST")
assert response.status_code in (403, 405, 404)