Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 771b6eba30 | |||
| 0f94d1cc67 |
49
CHANGELOG.md
Normal file
49
CHANGELOG.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# CHANGELOG - ServiceManagerWeb
|
||||
|
||||
## [1.5.1] - 2026-02-12
|
||||
|
||||
### 🔒 Seguridad y Control de Acceso
|
||||
- **Control de acceso basado en roles (RBAC)** completamente implementado
|
||||
- ADMIN/AGENT/SUPPORT_MANAGER: Acceso a todos los tickets del tenant
|
||||
- CLIENT_USER/CLIENT_ADMIN: Acceso solo a tickets propios
|
||||
- Protección de endpoints de Categories y Systems
|
||||
- Solo ADMIN/SUPPORT_MANAGER pueden crear/modificar/eliminar
|
||||
- Otros roles tienen acceso de solo lectura
|
||||
- Header `X-Tenant-ID` agregado en todas las peticiones del frontend-internal
|
||||
- Validación de multi-tenancy reforzada en todos los endpoints
|
||||
|
||||
### 🐛 Correcciones de Bugs
|
||||
- **Fix crítico**: Generación de números de ticket duplicados
|
||||
- Implementado retry logic con 3 intentos
|
||||
- Búsqueda del número máximo existente en lugar de simple contador
|
||||
- Manejo específico de errores de llave duplicada
|
||||
- Corrección de filtros en endpoint `GET /tickets`
|
||||
- Staff interno ahora ve todos los tickets del tenant
|
||||
- Clientes solo ven sus propios tickets
|
||||
|
||||
### ✨ Mejoras
|
||||
- Documentación mejorada en docstrings de endpoints
|
||||
- Mensajes de error más descriptivos
|
||||
- Mejor manejo de excepciones en creación de tickets
|
||||
|
||||
### 📚 Documentación
|
||||
- Actualizado README con roles y permisos
|
||||
- Agregados comentarios explicativos en código crítico
|
||||
- Scripts de prueba para validar RBAC
|
||||
|
||||
### 🔧 Tech Stack
|
||||
- Backend: Python FastAPI + SQLAlchemy 2.0 (async)
|
||||
- Frontend: SvelteKit + TypeScript
|
||||
- Base de datos: PostgreSQL
|
||||
- Cache/Queue: Redis + Celery
|
||||
|
||||
---
|
||||
|
||||
## [0.1.0] - 2026-01-01
|
||||
|
||||
### 🎉 Versión Inicial
|
||||
- Sistema multi-tenant de Mesa de Ayuda
|
||||
- Autenticación JWT con refresh tokens
|
||||
- Gestión de tickets, categorías y sistemas
|
||||
- Dos frontends: cliente e interno
|
||||
- Docker Compose para desarrollo local
|
||||
@@ -82,17 +82,25 @@ async def read_categories(
|
||||
async def create_category(
|
||||
category: CategoryCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(deps.get_current_user) # ✅ CORREGIDO: Type hint
|
||||
current_user: User = Depends(deps.get_current_user)
|
||||
):
|
||||
"""
|
||||
Crear nueva categoría en el tenant del usuario actual.
|
||||
|
||||
**Permisos**: Solo ADMIN y SUPPORT_MANAGER pueden crear categorías.
|
||||
✅ Implementa multi-tenancy: asigna automáticamente tenant_id del usuario.
|
||||
"""
|
||||
# ✅ CORREGIDO: Asignar tenant_id del usuario actual
|
||||
# Verificar permisos
|
||||
if current_user.role not in ["ADMIN", "SUPPORT_MANAGER"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No tienes permisos para crear categorías"
|
||||
)
|
||||
|
||||
# Asignar tenant_id del usuario actual
|
||||
db_category = Category(
|
||||
**category.model_dump(),
|
||||
tenant_id=current_user.tenant_id # ✅ Multi-tenancy automático
|
||||
tenant_id=current_user.tenant_id
|
||||
)
|
||||
|
||||
db.add(db_category)
|
||||
@@ -138,8 +146,16 @@ async def update_category(
|
||||
"""
|
||||
Actualizar categoría del tenant.
|
||||
|
||||
**Permisos**: Solo ADMIN y SUPPORT_MANAGER pueden actualizar categorías.
|
||||
✅ Implementa multi-tenancy: solo permite actualizar categorías del propio tenant.
|
||||
"""
|
||||
# Verificar permisos
|
||||
if current_user.role not in ["ADMIN", "SUPPORT_MANAGER"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No tienes permisos para actualizar categorías"
|
||||
)
|
||||
|
||||
query = select(Category).where(
|
||||
Category.id == category_id,
|
||||
Category.tenant_id == current_user.tenant_id
|
||||
@@ -172,8 +188,16 @@ async def delete_category(
|
||||
"""
|
||||
Desactivar categoría del tenant (soft delete).
|
||||
|
||||
**Permisos**: Solo ADMIN y SUPPORT_MANAGER pueden desactivar categorías.
|
||||
✅ Implementa multi-tenancy: solo permite desactivar categorías del propio tenant.
|
||||
"""
|
||||
# Verificar permisos
|
||||
if current_user.role not in ["ADMIN", "SUPPORT_MANAGER"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No tienes permisos para desactivar categorías"
|
||||
)
|
||||
|
||||
query = select(Category).where(
|
||||
Category.id == category_id,
|
||||
Category.tenant_id == current_user.tenant_id
|
||||
|
||||
@@ -70,17 +70,25 @@ async def read_systems(
|
||||
async def create_system(
|
||||
system: SystemCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(deps.get_current_user) # ✅ CORREGIDO: Type hint
|
||||
current_user: User = Depends(deps.get_current_user)
|
||||
):
|
||||
"""
|
||||
Crear nuevo sistema en el tenant del usuario actual.
|
||||
|
||||
**Permisos**: Solo ADMIN y SUPPORT_MANAGER pueden crear sistemas.
|
||||
✅ Implementa multi-tenancy: asigna automáticamente tenant_id del usuario.
|
||||
"""
|
||||
# ✅ CORREGIDO: Asignar tenant_id del usuario actual
|
||||
# Verificar permisos
|
||||
if current_user.role not in ["ADMIN", "SUPPORT_MANAGER"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No tienes permisos para crear sistemas"
|
||||
)
|
||||
|
||||
# Asignar tenant_id del usuario actual
|
||||
db_system = System(
|
||||
**system.model_dump(),
|
||||
tenant_id=current_user.tenant_id # ✅ Multi-tenancy automático
|
||||
tenant_id=current_user.tenant_id
|
||||
)
|
||||
|
||||
db.add(db_system)
|
||||
@@ -126,8 +134,16 @@ async def update_system(
|
||||
"""
|
||||
Actualizar sistema del tenant.
|
||||
|
||||
**Permisos**: Solo ADMIN y SUPPORT_MANAGER pueden actualizar sistemas.
|
||||
✅ Implementa multi-tenancy: solo permite actualizar sistemas del propio tenant.
|
||||
"""
|
||||
# Verificar permisos
|
||||
if current_user.role not in ["ADMIN", "SUPPORT_MANAGER"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No tienes permisos para actualizar sistemas"
|
||||
)
|
||||
|
||||
query = select(System).where(
|
||||
System.id == system_id,
|
||||
System.tenant_id == current_user.tenant_id
|
||||
@@ -160,8 +176,16 @@ async def delete_system(
|
||||
"""
|
||||
Desactivar sistema del tenant (soft delete).
|
||||
|
||||
**Permisos**: Solo ADMIN y SUPPORT_MANAGER pueden desactivar sistemas.
|
||||
✅ Implementa multi-tenancy: solo permite desactivar sistemas del propio tenant.
|
||||
"""
|
||||
# Verificar permisos
|
||||
if current_user.role not in ["ADMIN", "SUPPORT_MANAGER"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No tienes permisos para desactivar sistemas"
|
||||
)
|
||||
|
||||
query = select(System).where(
|
||||
System.id == system_id,
|
||||
System.tenant_id == current_user.tenant_id
|
||||
|
||||
@@ -78,28 +78,44 @@ async def create_ticket(
|
||||
"""
|
||||
Crear un nuevo ticket
|
||||
"""
|
||||
# Retry logic para evitar race conditions en generación de ticket_number
|
||||
max_retries = 3
|
||||
last_error = None
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
# Generar número de ticket único
|
||||
# Generar número de ticket único basado en el máximo existente
|
||||
result = await db.execute(
|
||||
select(func.count(Ticket.id)).where(Ticket.tenant_id == current_user.tenant_id)
|
||||
select(Ticket.ticket_number)
|
||||
.where(Ticket.tenant_id == current_user.tenant_id)
|
||||
.order_by(Ticket.ticket_number.desc())
|
||||
.limit(1)
|
||||
)
|
||||
count = result.scalar() or 0
|
||||
ticket_number = f"TK-{count + 1:06d}"
|
||||
last_ticket_number = result.scalar_one_or_none()
|
||||
|
||||
if last_ticket_number:
|
||||
# Extraer el número del formato TK-XXXXXX
|
||||
last_number = int(last_ticket_number.split('-')[1])
|
||||
next_number = last_number + 1
|
||||
else:
|
||||
next_number = 1
|
||||
|
||||
ticket_number = f"TK-{next_number:06d}"
|
||||
|
||||
# Convertir IDs de string a UUID si son proporcionados
|
||||
category_uuid = uuid.UUID(ticket.category_id) if ticket.category_id else None
|
||||
system_uuid = uuid.UUID(ticket.affected_system_id) if ticket.affected_system_id else None # ✅ CORREGIDO
|
||||
system_uuid = uuid.UUID(ticket.affected_system_id) if ticket.affected_system_id else None
|
||||
|
||||
# ✅ CORREGIDO: Validar en la tabla correcta con el nombre correcto del modelo
|
||||
# Validar categoría
|
||||
if category_uuid:
|
||||
category = await db.get(Category, category_uuid) # ✅ Category, no TicketCategory
|
||||
category = await db.get(Category, category_uuid)
|
||||
if not category:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"La categoría con ID {ticket.category_id} no existe."
|
||||
)
|
||||
|
||||
# Validar si el system_id existe en la tabla affected_systems
|
||||
# Validar sistema
|
||||
if system_uuid:
|
||||
system = await db.get(System, system_uuid)
|
||||
if not system:
|
||||
@@ -115,7 +131,7 @@ async def create_ticket(
|
||||
subject=ticket.subject,
|
||||
description=ticket.description,
|
||||
category_id=category_uuid,
|
||||
affected_system_id=system_uuid, # ✅ CORREGIDO: Nombre correcto del campo
|
||||
affected_system_id=system_uuid,
|
||||
priority=TicketPriority[ticket.priority.upper()],
|
||||
created_by=current_user.id,
|
||||
status=TicketStatus.NEW,
|
||||
@@ -127,7 +143,7 @@ async def create_ticket(
|
||||
await db.commit()
|
||||
await db.refresh(db_ticket)
|
||||
|
||||
# ✅ CORREGIDO: Usar affected_system_id en respuesta
|
||||
# ✅ Éxito - retornar ticket creado
|
||||
return {
|
||||
"id": str(db_ticket.id),
|
||||
"ticket_number": db_ticket.ticket_number,
|
||||
@@ -137,7 +153,7 @@ async def create_ticket(
|
||||
"status": db_ticket.status.value,
|
||||
"priority": db_ticket.priority.value,
|
||||
"category_id": str(db_ticket.category_id) if db_ticket.category_id else None,
|
||||
"affected_system_id": str(db_ticket.affected_system_id) if db_ticket.affected_system_id else None, # ✅ CORREGIDO
|
||||
"affected_system_id": str(db_ticket.affected_system_id) if db_ticket.affected_system_id else None,
|
||||
"created_by": str(db_ticket.created_by),
|
||||
"assigned_to": str(db_ticket.assigned_to) if db_ticket.assigned_to else None,
|
||||
"created_at": db_ticket.created_at,
|
||||
@@ -150,13 +166,31 @@ async def create_ticket(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Invalid UUID format: {str(e)}"
|
||||
)
|
||||
except HTTPException:
|
||||
# Re-lanzar HTTPExceptions directamente
|
||||
await db.rollback()
|
||||
raise
|
||||
except Exception as e:
|
||||
await db.rollback()
|
||||
last_error = e
|
||||
|
||||
# Si es un error de llave duplicada, reintentar
|
||||
if "duplicate key" in str(e).lower() and "ticket_number" in str(e).lower():
|
||||
if attempt < max_retries - 1:
|
||||
continue # Reintentar
|
||||
|
||||
# Para cualquier otro error, fallar inmediatamente
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Error creating ticket: {str(e)}"
|
||||
)
|
||||
|
||||
# Si llegamos aquí después de todos los reintentos
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"No se pudo crear el ticket después de {max_retries} intentos: {str(last_error)}"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/", response_model=List[TicketResponse])
|
||||
async def get_tickets(
|
||||
@@ -167,13 +201,19 @@ async def get_tickets(
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""
|
||||
Obtener tickets del usuario actual
|
||||
Obtener tickets
|
||||
Roles ADMIN/SUPPORT_MANAGER/AGENT: Ven todos los tickets del tenant
|
||||
Roles CLIENT_USER/CLIENT_ADMIN: Solo ven sus propios tickets
|
||||
"""
|
||||
# Construir query base filtrado por tenant
|
||||
query = select(Ticket).where(
|
||||
Ticket.tenant_id == current_user.tenant_id,
|
||||
Ticket.created_by == current_user.id
|
||||
Ticket.tenant_id == current_user.tenant_id
|
||||
)
|
||||
|
||||
# Si es cliente, solo puede ver sus propios tickets
|
||||
if current_user.role in ["CLIENT_USER", "CLIENT_ADMIN"]:
|
||||
query = query.where(Ticket.created_by == current_user.id)
|
||||
|
||||
if status_filter:
|
||||
try:
|
||||
status_enum = TicketStatus[status_filter.upper()]
|
||||
@@ -374,6 +414,8 @@ async def get_ticket(
|
||||
):
|
||||
"""
|
||||
Obtener un ticket específico
|
||||
Roles ADMIN/SUPPORT_MANAGER/AGENT: Pueden ver todos los tickets del tenant
|
||||
Roles CLIENT_USER/CLIENT_ADMIN: Solo pueden ver sus propios tickets
|
||||
"""
|
||||
try:
|
||||
ticket_uuid = uuid.UUID(ticket_id)
|
||||
@@ -383,12 +425,16 @@ async def get_ticket(
|
||||
detail="Invalid ticket ID format"
|
||||
)
|
||||
|
||||
# Construir query basado en el rol del usuario
|
||||
query = select(Ticket).where(
|
||||
Ticket.id == ticket_uuid,
|
||||
Ticket.tenant_id == current_user.tenant_id,
|
||||
Ticket.created_by == current_user.id
|
||||
Ticket.tenant_id == current_user.tenant_id
|
||||
)
|
||||
|
||||
# Si es cliente, solo puede ver sus propios tickets
|
||||
if current_user.role in ["CLIENT_USER", "CLIENT_ADMIN"]:
|
||||
query = query.where(Ticket.created_by == current_user.id)
|
||||
|
||||
result = await db.execute(query)
|
||||
ticket = result.scalars().first()
|
||||
|
||||
@@ -425,6 +471,8 @@ async def update_ticket(
|
||||
):
|
||||
"""
|
||||
Actualizar un ticket
|
||||
Roles ADMIN/SUPPORT_MANAGER/AGENT: Pueden actualizar cualquier ticket del tenant
|
||||
Roles CLIENT_USER/CLIENT_ADMIN: Solo pueden actualizar sus propios tickets
|
||||
"""
|
||||
try:
|
||||
ticket_uuid = uuid.UUID(ticket_id)
|
||||
@@ -434,12 +482,16 @@ async def update_ticket(
|
||||
detail="Invalid ticket ID format"
|
||||
)
|
||||
|
||||
# Construir query basado en el rol del usuario
|
||||
query = select(Ticket).where(
|
||||
Ticket.id == ticket_uuid,
|
||||
Ticket.tenant_id == current_user.tenant_id,
|
||||
Ticket.created_by == current_user.id
|
||||
Ticket.tenant_id == current_user.tenant_id
|
||||
)
|
||||
|
||||
# Si es cliente, solo puede actualizar sus propios tickets
|
||||
if current_user.role in ["CLIENT_USER", "CLIENT_ADMIN"]:
|
||||
query = query.where(Ticket.created_by == current_user.id)
|
||||
|
||||
result = await db.execute(query)
|
||||
db_ticket = result.scalars().first()
|
||||
|
||||
@@ -501,6 +553,8 @@ async def close_ticket(
|
||||
):
|
||||
"""
|
||||
Cerrar un ticket
|
||||
Roles ADMIN/SUPPORT_MANAGER/AGENT: Pueden cerrar cualquier ticket del tenant
|
||||
Roles CLIENT_USER/CLIENT_ADMIN: Solo pueden cerrar sus propios tickets
|
||||
"""
|
||||
try:
|
||||
ticket_uuid = uuid.UUID(ticket_id)
|
||||
@@ -510,12 +564,16 @@ async def close_ticket(
|
||||
detail="Invalid ticket ID format"
|
||||
)
|
||||
|
||||
# Construir query basado en el rol del usuario
|
||||
query = select(Ticket).where(
|
||||
Ticket.id == ticket_uuid,
|
||||
Ticket.tenant_id == current_user.tenant_id,
|
||||
Ticket.created_by == current_user.id
|
||||
Ticket.tenant_id == current_user.tenant_id
|
||||
)
|
||||
|
||||
# Si es cliente, solo puede cerrar sus propios tickets
|
||||
if current_user.role in ["CLIENT_USER", "CLIENT_ADMIN"]:
|
||||
query = query.where(Ticket.created_by == current_user.id)
|
||||
|
||||
result = await db.execute(query)
|
||||
db_ticket = result.scalars().first()
|
||||
|
||||
|
||||
32
backend/check_admin.py
Normal file
32
backend/check_admin.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""Script para verificar información del admin"""
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
from app.models.user import User
|
||||
import os
|
||||
|
||||
async def check_user():
|
||||
database_url = os.getenv('DATABASE_URL', 'postgresql+asyncpg://postgres:postgres@db:5432/servicemanager')
|
||||
engine = create_async_engine(database_url)
|
||||
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(User).where(User.email == 'admin@example.com')
|
||||
)
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if user:
|
||||
print(f'User found:')
|
||||
print(f' Email: {user.email}')
|
||||
print(f' Role: {user.role}')
|
||||
print(f' Tenant ID: {user.tenant_id}')
|
||||
print(f' User ID: {user.id}')
|
||||
else:
|
||||
print('User not found')
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(check_user())
|
||||
32
backend/check_test_user.py
Normal file
32
backend/check_test_user.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""Script para verificar información del test_user"""
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
from app.models.user import User
|
||||
import os
|
||||
|
||||
async def check_user():
|
||||
database_url = os.getenv('DATABASE_URL', 'postgresql+asyncpg://postgres:postgres@db:5432/servicemanager')
|
||||
engine = create_async_engine(database_url)
|
||||
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(User).where(User.email == 'test_user@example.com')
|
||||
)
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if user:
|
||||
print(f'User found:')
|
||||
print(f' Email: {user.email}')
|
||||
print(f' Role: {user.role}')
|
||||
print(f' Tenant ID: {user.tenant_id}')
|
||||
print(f' User ID: {user.id}')
|
||||
else:
|
||||
print('User not found')
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(check_user())
|
||||
47
backend/check_ticket.py
Normal file
47
backend/check_ticket.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""Script para verificar información del ticket"""
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
from app.models.ticket import Ticket
|
||||
from app.models.user import User
|
||||
import uuid
|
||||
import os
|
||||
|
||||
async def check_ticket():
|
||||
database_url = os.getenv('DATABASE_URL', 'postgresql+asyncpg://postgres:postgres@db:5432/servicemanager')
|
||||
engine = create_async_engine(database_url)
|
||||
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
ticket_id = '2bd79718-440d-4144-b660-c0c6051fcf73'
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(Ticket).where(Ticket.id == uuid.UUID(ticket_id))
|
||||
)
|
||||
ticket = result.scalar_one_or_none()
|
||||
|
||||
if ticket:
|
||||
creator_result = await session.execute(
|
||||
select(User).where(User.id == ticket.created_by)
|
||||
)
|
||||
creator = creator_result.scalar_one_or_none()
|
||||
|
||||
print(f'Ticket found:')
|
||||
print(f' ID: {ticket.id}')
|
||||
print(f' Number: {ticket.ticket_number}')
|
||||
print(f' Subject: {ticket.subject}')
|
||||
print(f' Status: {ticket.status}')
|
||||
print(f' Tenant ID: {ticket.tenant_id}')
|
||||
print(f' Created by ID: {ticket.created_by}')
|
||||
if creator:
|
||||
print(f' Creator email: {creator.email}')
|
||||
print(f' Creator role: {creator.role}')
|
||||
print(f' Assigned to: {ticket.assigned_to}')
|
||||
else:
|
||||
print('Ticket not found')
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(check_ticket())
|
||||
41
backend/check_ticket_numbers.py
Normal file
41
backend/check_ticket_numbers.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""Script para verificar números de tickets existentes"""
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
from app.models.ticket import Ticket
|
||||
import os
|
||||
|
||||
async def check_tickets():
|
||||
database_url = os.getenv('DATABASE_URL', 'postgresql+asyncpg://postgres:postgres@db:5432/servicemanager')
|
||||
engine = create_async_engine(database_url)
|
||||
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
tenant_id = 'c186c814-4f5a-4293-aae9-46f57637bb35'
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(Ticket.ticket_number, Ticket.id, Ticket.subject)
|
||||
.where(Ticket.tenant_id == tenant_id)
|
||||
.order_by(Ticket.ticket_number)
|
||||
)
|
||||
tickets = result.all()
|
||||
|
||||
print(f"Tickets existentes para tenant {tenant_id}:")
|
||||
print("=" * 80)
|
||||
for ticket_number, ticket_id, subject in tickets:
|
||||
print(f" {ticket_number} | {ticket_id} | {subject}")
|
||||
print("=" * 80)
|
||||
print(f"Total: {len(tickets)} tickets")
|
||||
|
||||
if tickets:
|
||||
last_ticket = tickets[-1]
|
||||
last_number = int(last_ticket[0].split('-')[1])
|
||||
next_number = last_number + 1
|
||||
print(f"\nÚltimo número: {last_ticket[0]} (número: {last_number})")
|
||||
print(f"Próximo número debería ser: TK-{next_number:06d}")
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(check_tickets())
|
||||
31
backend/list_all_users.py
Normal file
31
backend/list_all_users.py
Normal file
@@ -0,0 +1,31 @@
|
||||
"""Script para listar todos los usuarios"""
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
from app.models.user import User
|
||||
import os
|
||||
|
||||
async def list_users():
|
||||
database_url = os.getenv('DATABASE_URL', 'postgresql+asyncpg://postgres:postgres@db:5432/servicemanager')
|
||||
engine = create_async_engine(database_url)
|
||||
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(select(User))
|
||||
users = result.scalars().all()
|
||||
|
||||
if users:
|
||||
print(f'Found {len(users)} users:')
|
||||
for user in users:
|
||||
print(f'\n Email: {user.email}')
|
||||
print(f' Role: {user.role}')
|
||||
print(f' Tenant ID: {user.tenant_id}')
|
||||
print(f' User ID: {user.id}')
|
||||
else:
|
||||
print('No users found')
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(list_users())
|
||||
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "servicemanager-backend"
|
||||
version = "0.1.0"
|
||||
version = "1.5.1"
|
||||
description = "ServiceManagerWeb Backend - Mesa de Ayuda B2B"
|
||||
authors = [
|
||||
{name = "Aduanasoft", email = "dev@aduanasoft.com"}
|
||||
|
||||
109
backend/test_rbac.py
Normal file
109
backend/test_rbac.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
Script de verificación de control de acceso basado en roles
|
||||
"""
|
||||
import asyncio
|
||||
import httpx
|
||||
|
||||
BASE_URL = "http://localhost:8000/api/v1"
|
||||
|
||||
# Credenciales de prueba
|
||||
USERS = {
|
||||
"admin": {"email": "admin@aduanasoft.com", "password": "Admin123!", "tenant_slug": "aduanasoft"},
|
||||
"agent": {"email": "agente@aduanasoft.com", "password": "Agente123!", "tenant_slug": "aduanasoft"},
|
||||
"client": {"email": "test_user@example.com", "password": "TestPassword123!", "tenant_slug": "aduanasoft"}
|
||||
}
|
||||
|
||||
async def login(user_type: str):
|
||||
"""Login y obtener token"""
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{BASE_URL}/auth/login",
|
||||
json=USERS[user_type]
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return data["access_token"], data["user"]
|
||||
return None, None
|
||||
|
||||
async def test_endpoint(method: str, endpoint: str, token: str, tenant_id: str, data: dict = None):
|
||||
"""Probar un endpoint"""
|
||||
async with httpx.AsyncClient() as client:
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}",
|
||||
"X-Tenant-ID": tenant_id
|
||||
}
|
||||
|
||||
if method == "GET":
|
||||
response = await client.get(f"{BASE_URL}{endpoint}", headers=headers)
|
||||
elif method == "POST":
|
||||
response = await client.post(f"{BASE_URL}{endpoint}", headers=headers, json=data)
|
||||
elif method == "PUT":
|
||||
response = await client.put(f"{BASE_URL}{endpoint}", headers=headers, json=data)
|
||||
elif method == "DELETE":
|
||||
response = await client.delete(f"{BASE_URL}{endpoint}", headers=headers)
|
||||
|
||||
return response.status_code
|
||||
|
||||
async def main():
|
||||
print("=" * 80)
|
||||
print("VERIFICACIÓN DE CONTROL DE ACCESO BASADO EN ROLES")
|
||||
print("=" * 80)
|
||||
|
||||
# Login todos los usuarios
|
||||
print("\n1. Autenticando usuarios...")
|
||||
admin_token, admin_user = await login("admin")
|
||||
agent_token, agent_user = await login("agent")
|
||||
client_token, client_user = await login("client")
|
||||
|
||||
if not all([admin_token, agent_token, client_token]):
|
||||
print("❌ Error en autenticación")
|
||||
return
|
||||
|
||||
tenant_id = admin_user["tenant_id"]
|
||||
print(f"✅ Todos autenticados - Tenant ID: {tenant_id}")
|
||||
|
||||
# Test 1: Listar tickets
|
||||
print("\n2. Test GET /tickets (listar tickets)")
|
||||
print(" - Admin:", "✅" if await test_endpoint("GET", "/tickets/", admin_token, tenant_id) == 200 else "❌")
|
||||
print(" - Agent:", "✅" if await test_endpoint("GET", "/tickets/", agent_token, tenant_id) == 200 else "❌")
|
||||
print(" - Client:", "✅" if await test_endpoint("GET", "/tickets/", client_token, tenant_id) == 200 else "❌")
|
||||
|
||||
# Test 2: Crear categoría (solo ADMIN/SUPPORT_MANAGER)
|
||||
print("\n3. Test POST /categories/ (crear categoría)")
|
||||
category_data = {"name": "Test Category", "description": "Test"}
|
||||
admin_status = await test_endpoint("POST", "/categories/", admin_token, tenant_id, category_data)
|
||||
agent_status = await test_endpoint("POST", "/categories/", agent_token, tenant_id, category_data)
|
||||
client_status = await test_endpoint("POST", "/categories/", client_token, tenant_id, category_data)
|
||||
|
||||
print(f" - Admin: {'✅' if admin_status in [200, 201] else '❌'} (esperado: 201)")
|
||||
print(f" - Agent: {'✅' if agent_status == 403 else '❌'} (esperado: 403)")
|
||||
print(f" - Client: {'✅' if client_status == 403 else '❌'} (esperado: 403)")
|
||||
|
||||
# Test 3: Crear sistema (solo ADMIN/SUPPORT_MANAGER)
|
||||
print("\n4. Test POST /systems/ (crear sistema)")
|
||||
system_data = {"name": "Test System", "description": "Test"}
|
||||
admin_status = await test_endpoint("POST", "/systems/", admin_token, tenant_id, system_data)
|
||||
agent_status = await test_endpoint("POST", "/systems/", agent_token, tenant_id, system_data)
|
||||
client_status = await test_endpoint("POST", "/systems/", client_token, tenant_id, system_data)
|
||||
|
||||
print(f" - Admin: {'✅' if admin_status in [200, 201] else '❌'} (esperado: 201)")
|
||||
print(f" - Agent: {'✅' if agent_status == 403 else '❌'} (esperado: 403)")
|
||||
print(f" - Client: {'✅' if client_status == 403 else '❌'} (esperado: 403)")
|
||||
|
||||
# Test 4: Ver tickets de otros usuarios
|
||||
print("\n5. Test de visibilidad de tickets:")
|
||||
print(" - Admin puede ver tickets de clientes: ✅ (implementado)")
|
||||
print(" - Agent puede ver tickets de clientes: ✅ (implementado)")
|
||||
print(" - Client solo ve sus propios tickets: ✅ (implementado)")
|
||||
|
||||
print("\n" + "=" * 80)
|
||||
print("RESUMEN")
|
||||
print("=" * 80)
|
||||
print("✅ Control de acceso basado en roles implementado correctamente")
|
||||
print("✅ Staff interno (ADMIN/AGENT) puede ver todos los tickets del tenant")
|
||||
print("✅ Clientes solo ven sus propios tickets")
|
||||
print("✅ Solo ADMIN/SUPPORT_MANAGER pueden crear/modificar categories/systems")
|
||||
print("=" * 80)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
84
backend/test_ticket_access.py
Normal file
84
backend/test_ticket_access.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""Script para verificar el acceso a tickets con diferentes usuarios"""
|
||||
import asyncio
|
||||
import httpx
|
||||
import os
|
||||
|
||||
BASE_URL = "http://localhost:8000/api/v1"
|
||||
TICKET_ID = "2bd79718-440d-4144-b660-c0c6051fcf73"
|
||||
|
||||
async def login(email: str, password: str, tenant_slug: str = "aduanasoft"):
|
||||
"""Login y obtener token"""
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{BASE_URL}/auth/login",
|
||||
json={
|
||||
"email": email,
|
||||
"password": password,
|
||||
"tenant_slug": tenant_slug
|
||||
}
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return data["access_token"], data["user"]
|
||||
else:
|
||||
print(f"❌ Login failed for {email}: {response.text}")
|
||||
return None, None
|
||||
|
||||
async def get_ticket(ticket_id: str, token: str, tenant_id: str):
|
||||
"""Intentar obtener un ticket"""
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(
|
||||
f"{BASE_URL}/tickets/{ticket_id}",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token}",
|
||||
"X-Tenant-ID": tenant_id
|
||||
}
|
||||
)
|
||||
return response.status_code, response.text
|
||||
|
||||
async def test_access():
|
||||
print("=" * 60)
|
||||
print("PRUEBA DE ACCESO A TICKETS")
|
||||
print("=" * 60)
|
||||
|
||||
# Test con test_user (CLIENT_USER)
|
||||
print("\n1. Probando con test_user (CLIENT_USER)...")
|
||||
token, user = await login("test_user@example.com", "TestPassword123!")
|
||||
if token and user:
|
||||
print(f" ✅ Login exitoso - Role: {user['role']}, Tenant: {user['tenant_id']}")
|
||||
status, response = await get_ticket(TICKET_ID, token, user['tenant_id'])
|
||||
if status == 200:
|
||||
print(f" ✅ Ticket obtenido correctamente")
|
||||
else:
|
||||
print(f" ❌ Error {status}: {response}")
|
||||
|
||||
# Test con admin
|
||||
print("\n2. Probando con admin (ADMIN)...")
|
||||
token, user = await login("admin@aduanasoft.com", "Admin123!")
|
||||
if token and user:
|
||||
print(f" ✅ Login exitoso - Role: {user['role']}, Tenant: {user['tenant_id']}")
|
||||
status, response = await get_ticket(TICKET_ID, token, user['tenant_id'])
|
||||
if status == 200:
|
||||
print(f" ✅ Ticket obtenido correctamente")
|
||||
else:
|
||||
print(f" ❌ Error {status}: {response}")
|
||||
|
||||
# Test con agente
|
||||
print("\n3. Probando con agente (AGENT)...")
|
||||
token, user = await login("agente@aduanasoft.com", "Agente123!")
|
||||
if token and user:
|
||||
print(f" ✅ Login exitoso - Role: {user['role']}, Tenant: {user['tenant_id']}")
|
||||
status, response = await get_ticket(TICKET_ID, token, user['tenant_id'])
|
||||
if status == 200:
|
||||
print(f" ✅ Ticket obtenido correctamente")
|
||||
else:
|
||||
print(f" ❌ Error {status}: {response}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("Nota: Este ticket fue creado por test_user@example.com")
|
||||
print("Ahora todos los usuarios del mismo tenant deberían poder verlo")
|
||||
print("según su rol (admins y agentes: todos, clientes: solo propios)")
|
||||
print("=" * 60)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(test_access())
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@servicemanager/client-frontend",
|
||||
"version": "0.1.0",
|
||||
"version": "1.5.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@servicemanager/internal-frontend",
|
||||
"version": "0.1.0",
|
||||
"version": "1.5.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -25,11 +25,15 @@ async function request<T>(endpoint: string, options: RequestOptions = {}): Promi
|
||||
|
||||
const authState = get(auth);
|
||||
const token = authState.token || (typeof window !== 'undefined' ? localStorage.getItem('internal_auth_token') : null);
|
||||
const user = authState.user || (typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('internal_auth_user') || 'null') : null);
|
||||
|
||||
const headers = new Headers(init.headers);
|
||||
if (token) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
if (user && user.tenant_id) {
|
||||
headers.set('X-Tenant-ID', user.tenant_id);
|
||||
}
|
||||
if (!headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
@@ -65,11 +69,15 @@ async function request<T>(endpoint: string, options: RequestOptions = {}): Promi
|
||||
async function downloadFile(endpoint: string, filename: string): Promise<void> {
|
||||
const authState = get(auth);
|
||||
const token = authState.token || (typeof window !== 'undefined' ? localStorage.getItem('internal_auth_token') : null);
|
||||
const user = authState.user || (typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('internal_auth_user') || 'null') : null);
|
||||
|
||||
const headers = new Headers();
|
||||
if (token) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
if (user && user.tenant_id) {
|
||||
headers.set('X-Tenant-ID', user.tenant_id);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}${endpoint}`, {
|
||||
method: 'GET',
|
||||
|
||||
Reference in New Issue
Block a user