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:
@@ -1,10 +1,10 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import ConfigDict
|
||||
|
||||
|
||||
class SectorDTO(BaseModel):
|
||||
key: str = Field(..., min_length=1, max_length=8)
|
||||
description: str
|
||||
authorized: int
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
@@ -2,16 +2,21 @@ from sqlalchemy import String, SmallInteger, PrimaryKeyConstraint
|
||||
from sqlalchemy.orm import mapped_column, Mapped
|
||||
from core.database import Base
|
||||
|
||||
|
||||
class Sector(Base):
|
||||
__tablename__ = "sectors" #GSectores
|
||||
__tablename__ = "sectors" # GSectores
|
||||
__table_args__ = (
|
||||
PrimaryKeyConstraint("key", name="sectors_pkey"),
|
||||
{"schema": "public"} # opcional
|
||||
{"schema": "public"}, # opcional
|
||||
)
|
||||
|
||||
key: Mapped[str] = mapped_column(String(8), nullable=False) # clave del sector
|
||||
description: Mapped[str] = mapped_column(String(150), nullable=False) # descripción oficial (en español)
|
||||
authorized: Mapped[SmallInteger] = mapped_column(SmallInteger) # 1 = autorizado, 0 = no autorizado
|
||||
key: Mapped[str] = mapped_column(String(8), nullable=False) # clave del sector
|
||||
description: Mapped[str] = mapped_column(
|
||||
String(150), nullable=False
|
||||
) # descripción oficial (en español)
|
||||
authorized: Mapped[SmallInteger] = mapped_column(
|
||||
SmallInteger
|
||||
) # 1 = autorizado, 0 = no autorizado
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Sector(key={self.key}, description={self.description}, authorized={self.authorized})>"
|
||||
|
||||
@@ -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_sectors(
|
||||
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(Sector)
|
||||
@@ -26,21 +25,27 @@ def list_sectors(
|
||||
"items": [SectorDTO.model_validate(obj) for obj in items],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size
|
||||
"page_size": page_size,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{key}", response_model=SectorDTO)
|
||||
def get_sector(key: str, db: Session = Depends(get_core_db), current_user: dict = Depends(get_current_user)):
|
||||
def get_sector(
|
||||
key: str,
|
||||
db: Session = Depends(get_core_db),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
):
|
||||
obj = db.query(Sector).filter(Sector.key == key).first()
|
||||
if not obj:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
return obj
|
||||
|
||||
|
||||
@router.post("/", response_model=SectorDTO, status_code=201)
|
||||
def create_sector(
|
||||
data: SectorDTO,
|
||||
db: Session = Depends(get_core_db),
|
||||
current_user: dict = Depends(has_role("admin"))
|
||||
current_user: dict = Depends(has_role("admin")),
|
||||
):
|
||||
obj = Sector(**data.dict())
|
||||
db.add(obj)
|
||||
@@ -48,12 +53,13 @@ def create_sector(
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
@router.put("/{key}", response_model=SectorDTO)
|
||||
def update_sector(
|
||||
key: str,
|
||||
data: SectorDTO,
|
||||
db: Session = Depends(get_core_db),
|
||||
current_user: dict = Depends(has_role("admin"))
|
||||
current_user: dict = Depends(has_role("admin")),
|
||||
):
|
||||
obj = db.query(Sector).filter(Sector.key == key).first()
|
||||
if not obj:
|
||||
@@ -64,11 +70,12 @@ def update_sector(
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
@router.delete("/{key}", status_code=204)
|
||||
def delete_sector(
|
||||
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(Sector).filter(Sector.key == key).first()
|
||||
if not obj:
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
seed = [
|
||||
("I", "INDUSTRIA ELECTRICA", "0"),
|
||||
("II", "INDUSTRIA ELECTRONICA", "0"),
|
||||
("IIa", "PARA LOS BIENES A QUE SE REFIERE LA FRACCION II, INCISO a) o b), DE ARTICULO 4to DE ESTE DECRETO.", "0"),
|
||||
("IIb", "PARA LOS BIENES A QUE SE REFIERE LA FRACCION II, INCISO b), DE ARTICULO 4to DE ESTE DECRETO.", "0"),
|
||||
(
|
||||
"IIa",
|
||||
"PARA LOS BIENES A QUE SE REFIERE LA FRACCION II, INCISO a) o b), DE ARTICULO 4to DE ESTE DECRETO.",
|
||||
"0",
|
||||
),
|
||||
(
|
||||
"IIb",
|
||||
"PARA LOS BIENES A QUE SE REFIERE LA FRACCION II, INCISO b), DE ARTICULO 4to DE ESTE DECRETO.",
|
||||
"0",
|
||||
),
|
||||
("III", "INDUSTRIA DEL MUEBLE", "0"),
|
||||
("IV", "INDUSTRIA DEL JUGUETE, JUEGOS DE RECREO Y ARTICULOS DEPORTIVOS", "0"),
|
||||
("IX", "INDUSTRIA DE MAQUINARIA AGRICOLA", "0"),
|
||||
@@ -18,9 +26,21 @@ seed = [
|
||||
("XIX", "INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES", "0"),
|
||||
("XIXa", "INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES", "0"),
|
||||
("XIXb", "INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES", "0"),
|
||||
("XV", "INDUSTRIA DEL TRANSPORTE, EXCEPTO EL SECTOR DE LA INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES", "0"),
|
||||
("XVa", "INDUSTRIA DEL TRANSPORTE, EXCEPTO EL SECTOR DE LA INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES.", "0"),
|
||||
("XVb", "INDUSTRIA DEL TRANSPORTE, EXCEPTO EL SECTOR DE LA INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES.", "0"),
|
||||
(
|
||||
"XV",
|
||||
"INDUSTRIA DEL TRANSPORTE, EXCEPTO EL SECTOR DE LA INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES",
|
||||
"0",
|
||||
),
|
||||
(
|
||||
"XVa",
|
||||
"INDUSTRIA DEL TRANSPORTE, EXCEPTO EL SECTOR DE LA INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES.",
|
||||
"0",
|
||||
),
|
||||
(
|
||||
"XVb",
|
||||
"INDUSTRIA DEL TRANSPORTE, EXCEPTO EL SECTOR DE LA INDUSTRIA AUTOMOTRIZ Y DE AUTOPARTES.",
|
||||
"0",
|
||||
),
|
||||
("XVI", "INDUSTRIA DEL PAPEL Y CARTON", "0"),
|
||||
("XVII", "INDUSTRIA DE LA MADERA", "0"),
|
||||
("XVIII", "INDUSTRIA DEL CUERO Y PIELES", "0"),
|
||||
@@ -32,4 +52,4 @@ seed = [
|
||||
("XXe", "INDUSTRIA TEXTIL Y DE LA CONFECCION", "0"),
|
||||
("XXI", "INDUSTRIA DE CHOCOLATES, DULCES Y SIMILARES", "0"),
|
||||
("XXII", "INDUSTRIA DEL CAFE", "0"),
|
||||
]
|
||||
]
|
||||
|
||||
@@ -7,6 +7,7 @@ app = FastAPI()
|
||||
app.include_router(router)
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("client", "access_token")
|
||||
def test_list_sectors(client, access_token):
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
@@ -16,20 +17,24 @@ def test_list_sectors(client, access_token):
|
||||
assert "page" in response.json()
|
||||
assert "page_size" in response.json()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("client", "access_token")
|
||||
def test_get_sector_not_found(client, access_token):
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
response = client.get("/sectors/invalid_key", headers=headers)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_create_sector_forbidden():
|
||||
response = client.post("/sectors/", json={"key": "TST", "description": "Test"})
|
||||
assert response.status_code in (403, 405, 404)
|
||||
|
||||
|
||||
def test_update_sector_forbidden():
|
||||
response = client.put("/sectors/TST", json={"key": "TST", "description": "Test"})
|
||||
assert response.status_code in (403, 405, 404)
|
||||
|
||||
|
||||
def test_delete_sector_forbidden():
|
||||
response = client.delete("/sectors/TST")
|
||||
assert response.status_code in (403, 405, 404)
|
||||
|
||||
Reference in New Issue
Block a user