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 PaymentMethodDTO(BaseModel):
key: str = Field(..., min_length=1, max_length=2)
description: str
model_config = ConfigDict(from_attributes=True)

View File

@@ -2,11 +2,12 @@ from sqlalchemy import String, PrimaryKeyConstraint
from sqlalchemy.orm import mapped_column, Mapped
from core.database import Base
class PaymentMethod(Base):
__tablename__ = "payment_methods" #GFormaPago
__tablename__ = "payment_methods" # GFormaPago
__table_args__ = (
PrimaryKeyConstraint("key", name="payment_methods_pkey"),
{"schema": "public"} # opcional
{"schema": "public"}, # opcional
)
key: Mapped[str] = mapped_column(String(2), 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
@@ -16,7 +15,7 @@ def list_payment_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(PaymentMethod)
@@ -26,21 +25,27 @@ def list_payment_methods(
"items": [PaymentMethodDTO.model_validate(obj) for obj in items],
"total": total,
"page": page,
"page_size": page_size
"page_size": page_size,
}
@router.get("/{key}", response_model=PaymentMethodDTO)
def get_payment_method(key: str, db: Session = Depends(get_core_db), current_user: dict = Depends(get_current_user)):
def get_payment_method(
key: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
obj = db.query(PaymentMethod).filter(PaymentMethod.key == key).first()
if not obj:
raise HTTPException(status_code=404, detail="Not found")
return obj
@router.post("/", response_model=PaymentMethodDTO, status_code=201)
def create_payment_method(
data: PaymentMethodDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(has_role("admin"))
current_user: dict = Depends(has_role("admin")),
):
obj = PaymentMethod(**data.dict())
db.add(obj)
@@ -48,12 +53,13 @@ def create_payment_method(
db.refresh(obj)
return obj
@router.put("/{key}", response_model=PaymentMethodDTO)
def update_payment_method(
key: str,
data: PaymentMethodDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(has_role("admin"))
current_user: dict = Depends(has_role("admin")),
):
obj = db.query(PaymentMethod).filter(PaymentMethod.key == key).first()
if not obj:
@@ -64,11 +70,12 @@ def update_payment_method(
db.refresh(obj)
return obj
@router.delete("/{key}", status_code=204)
def delete_payment_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(PaymentMethod).filter(PaymentMethod.key == key).first()
if not obj:

View File

@@ -10,7 +10,10 @@ seed = [
("18", "ESTIMULO FISCAL."),
("19", "OTROS MEDIOS DE GARANTIA."),
("2", "FIANZA."),
("20", "DEROGADA. --- (PAGO CONFORME AL ARTICULO 7 DE LA LEY DE INGRESOS DE LA FEDERACION, VIGENTE)"),
(
"20",
"DEROGADA. --- (PAGO CONFORME AL ARTICULO 7 DE LA LEY DE INGRESOS DE LA FEDERACION, VIGENTE)",
),
("21", "CRÉDITO EN IVA E IEPS."),
("22", "GARANTÍA EN IVA E IEPS."),
("4", "DEPOSITO EN CUENTA ADUANERA."),
@@ -19,4 +22,4 @@ seed = [
("7", "CARGO A PARTIDA PRESUPUESTAL GOBIERNO FEDERAL."),
("8", "FRANQUICIA."),
("9", "EXENTO DE PAGO."),
]
]

View File

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