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,6 +1,7 @@
from pydantic import BaseModel, Field
from pydantic import ConfigDict
class IncotermDTO(BaseModel):
code: str = Field(..., min_length=1, max_length=5)
description_es: str

View File

@@ -2,11 +2,12 @@ from sqlalchemy import String, PrimaryKeyConstraint
from sqlalchemy.orm import mapped_column, Mapped
from core.database import Base
class Incoterm(Base):
__tablename__ = "incoterms" #GIncoterm
__tablename__ = "incoterms" # GIncoterm
__table_args__ = (
PrimaryKeyConstraint("code", name="incoterms_pkey"),
{"schema": "public"}
{"schema": "public"},
)
code: Mapped[str] = mapped_column(String(5), nullable=False)

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="/incoterms")
@router.get("/", response_model=Dict[str, Any])
async def list_incoterms(
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(Incoterm)
@@ -27,23 +25,27 @@ async def list_incoterms(
"items": [IncotermDTO.model_validate(obj) for obj in items],
"total": total,
"page": page,
"page_size": page_size
"page_size": page_size,
}
@router.get("/{key}", response_model=IncotermDTO)
async def get_incoterm(key: str, db: Session = Depends(get_core_db), current_user: dict = Depends(get_current_user)):
async def get_incoterm(
key: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
obj = db.query(Incoterm).filter(Incoterm.code == key).first()
if not obj:
raise HTTPException(status_code=404, detail="Not found")
return IncotermDTO.model_validate(obj)
@router.post("/", response_model=IncotermDTO, status_code=201)
async def create_incoterm(
data: IncotermDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(has_role("admin"))
current_user: dict = Depends(has_role("admin")),
):
obj = Incoterm(**data.model_dump())
db.add(obj)
@@ -51,13 +53,13 @@ async def create_incoterm(
db.refresh(obj)
return IncotermDTO.model_validate(obj)
@router.put("/{key}", response_model=IncotermDTO)
async def update_incoterm(
key: str,
data: IncotermDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(has_role("admin"))
current_user: dict = Depends(has_role("admin")),
):
obj = db.query(Incoterm).filter(Incoterm.code == key).first()
if not obj:
@@ -68,12 +70,12 @@ async def update_incoterm(
db.refresh(obj)
return IncotermDTO.model_validate(obj)
@router.delete("/{key}", status_code=204)
async def delete_incoterm(
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(Incoterm).filter(Incoterm.key == key).first()
if not obj:

View File

@@ -10,4 +10,4 @@ seed = [
("FOB", "PUERTO DE EMBARQUE CONVENIDO", "FREE ON BOARD"),
("CFR", "COSTO Y FLETE", "COST AND FREIGHT"),
("CIF", "COSTO, SEGURO Y FLETE", "COST, INSURANCE AND FREIGHT"),
]
]

View File

@@ -7,6 +7,7 @@ app = FastAPI()
app.include_router(router)
client = TestClient(app)
@pytest.mark.usefixtures("client", "access_token")
def test_list_incoterms(client, access_token):
headers = {"Authorization": f"Bearer {access_token}"}
@@ -16,20 +17,24 @@ def test_list_incoterms(client, access_token):
assert "page" in response.json()
assert "page_size" in response.json()
@pytest.mark.usefixtures("client", "access_token")
def test_get_incoterm_not_found(client, access_token):
headers = {"Authorization": f"Bearer {access_token}"}
response = client.get("/incoterms/invalid_key", headers=headers)
assert response.status_code == 404
def test_create_incoterm_forbidden():
response = client.post("/incoterms/", json={"key": "TST", "description": "Test"})
assert response.status_code in (403, 405, 404)
def test_update_incoterm_forbidden():
response = client.put("/incoterms/TST", json={"key": "TST", "description": "Test"})
assert response.status_code in (403, 405, 404)
def test_delete_incoterm_forbidden():
response = client.delete("/incoterms/TST")
assert response.status_code in (403, 405, 404)