Compare commits
15 Commits
v1.5.1.2-a
...
v1.6.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 32cc8b6ccd | |||
| caeac3e96c | |||
| 6af80f1960 | |||
| 57944b364c | |||
| 3a061a005c | |||
| d9b783107f | |||
| 5a292daa0b | |||
| 87e094b668 | |||
| 2cb8b58808 | |||
| 9f973464b9 | |||
| 90f9c9c6e6 | |||
| 51a8515b40 | |||
| ff9a8998b2 | |||
| 2033a35a2b | |||
| 96cd09476c |
26
.gitignore
vendored
26
.gitignore
vendored
@@ -30,29 +30,3 @@ docker-compose.override.yml
|
|||||||
|
|
||||||
# Uploads
|
# Uploads
|
||||||
uploads/
|
uploads/
|
||||||
|
|
||||||
# Test Coverage
|
|
||||||
htmlcov/
|
|
||||||
.coverage
|
|
||||||
*.cover
|
|
||||||
.pytest_cache/
|
|
||||||
|
|
||||||
# Backups
|
|
||||||
backups/
|
|
||||||
*.backup
|
|
||||||
*.bak
|
|
||||||
|
|
||||||
# Temporary files
|
|
||||||
temp_*.txt
|
|
||||||
temp_*.py
|
|
||||||
*.tmp
|
|
||||||
*.swp
|
|
||||||
*~
|
|
||||||
|
|
||||||
# Debug/Test scripts (usar scripts/ en su lugar)
|
|
||||||
check_*.py
|
|
||||||
fix_*.py
|
|
||||||
list_*.py
|
|
||||||
add_*.py
|
|
||||||
set_*.py
|
|
||||||
test_*.ps1
|
|
||||||
|
|||||||
49
CHANGELOG.md
49
CHANGELOG.md
@@ -1,49 +0,0 @@
|
|||||||
# 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
|
|
||||||
34
README.md
34
README.md
@@ -94,40 +94,6 @@ docker-compose ps
|
|||||||
- API Docs: http://localhost:8000/docs
|
- API Docs: http://localhost:8000/docs
|
||||||
- Adminer (DB): http://localhost:8080
|
- Adminer (DB): http://localhost:8080
|
||||||
|
|
||||||
## Utilidades Administrativas
|
|
||||||
|
|
||||||
Para gestión y debugging de la base de datos, usa el script consolidado:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Ver todos los comandos disponibles
|
|
||||||
python scripts/db_utils.py --help
|
|
||||||
|
|
||||||
# Listar todos los usuarios
|
|
||||||
python scripts/db_utils.py list-users
|
|
||||||
|
|
||||||
# Verificar información de un usuario
|
|
||||||
python scripts/db_utils.py check-user admin@example.com
|
|
||||||
|
|
||||||
# Resetear contraseña de un usuario
|
|
||||||
python scripts/db_utils.py reset-password admin@example.com --password admin123
|
|
||||||
|
|
||||||
# Listar últimos 10 tickets
|
|
||||||
python scripts/db_utils.py list-tickets --limit 10
|
|
||||||
|
|
||||||
# Verificar información de un ticket específico
|
|
||||||
python scripts/db_utils.py check-ticket <TICKET_ID>
|
|
||||||
|
|
||||||
# Filtrar por tenant
|
|
||||||
python scripts/db_utils.py list-users --tenant-id <TENANT_UUID>
|
|
||||||
python scripts/db_utils.py list-tickets --tenant-id <TENANT_UUID>
|
|
||||||
```
|
|
||||||
|
|
||||||
**💡 Alternativas para debugging:**
|
|
||||||
- **PostgreSQL directo**: Conectarte con pgAdmin, DBeaver o `psql`
|
|
||||||
- **Python Shell**: `python -m asyncio` desde el directorio backend
|
|
||||||
- **Tests**: Crear tests específicos en `backend/tests/`
|
|
||||||
- **API Docs**: Usar Swagger UI en http://localhost:8000/docs
|
|
||||||
|
|
||||||
## Scripts de Desarrollo
|
## Scripts de Desarrollo
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -1,254 +0,0 @@
|
|||||||
# Release Notes - ServiceManagerWeb v1.5.1
|
|
||||||
**Fecha**: 12 de Febrero, 2026
|
|
||||||
**Rama**: main
|
|
||||||
**Commit**: 771b6eb
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📦 Información de la Versión
|
|
||||||
|
|
||||||
**Versión Anterior**: v1.4.1.4
|
|
||||||
**Versión Actual**: v1.5.1
|
|
||||||
**Tipo de Release**: Minor (Funcionalidades + Correcciones Críticas)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🔒 Seguridad y Control de Acceso
|
|
||||||
|
|
||||||
### Control de Acceso Basado en Roles (RBAC)
|
|
||||||
|
|
||||||
#### Implementación Completa
|
|
||||||
- **Staff Interno** (ADMIN, AGENT, SUPPORT_MANAGER)
|
|
||||||
- ✅ Acceso a todos los tickets del tenant
|
|
||||||
- ✅ Puede ver/modificar cualquier ticket
|
|
||||||
- ✅ Control total sobre recursos compartidos
|
|
||||||
|
|
||||||
- **Clientes** (CLIENT_USER, CLIENT_ADMIN)
|
|
||||||
- ✅ Acceso solo a sus propios tickets
|
|
||||||
- ✅ No pueden ver tickets de otros clientes del mismo tenant
|
|
||||||
- ✅ Restricciones adecuadas implementadas
|
|
||||||
|
|
||||||
#### Endpoints Protegidos
|
|
||||||
|
|
||||||
**Categories** (`/api/v1/categories`)
|
|
||||||
- GET: Todos los roles (lectura)
|
|
||||||
- POST/PUT/DELETE: Solo ADMIN y SUPPORT_MANAGER
|
|
||||||
|
|
||||||
**Systems** (`/api/v1/systems`)
|
|
||||||
- GET: Todos los roles (lectura)
|
|
||||||
- POST/PUT/DELETE: Solo ADMIN y SUPPORT_MANAGER
|
|
||||||
|
|
||||||
**Tickets** (`/api/v1/tickets`)
|
|
||||||
- GET (listado): Filtrado según rol
|
|
||||||
- GET (detalle): Validación de permisos por rol
|
|
||||||
- POST: Todos (según su alcance)
|
|
||||||
- PATCH/DELETE: Validación por rol y propiedad
|
|
||||||
|
|
||||||
### Multi-Tenancy Reforzado
|
|
||||||
|
|
||||||
- ✅ Header `X-Tenant-ID` agregado en frontend-internal
|
|
||||||
- ✅ Validación de tenant en todos los endpoints
|
|
||||||
- ✅ Aislamiento estricto de datos entre tenants
|
|
||||||
- ✅ Prevención de acceso cruzado entre organizaciones
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🐛 Correcciones Críticas
|
|
||||||
|
|
||||||
### Fix: Números de Ticket Duplicados
|
|
||||||
|
|
||||||
**Problema Original**:
|
|
||||||
- Generación de números con simple contador
|
|
||||||
- Race conditions en creación simultánea
|
|
||||||
- Violación de constraint unique `uq_tickets_tenant_number`
|
|
||||||
|
|
||||||
**Solución Implementada**:
|
|
||||||
```python
|
|
||||||
# Retry logic con 3 intentos
|
|
||||||
# Búsqueda del MAX número existente
|
|
||||||
# Manejo específico de errores de llave duplicada
|
|
||||||
for attempt in range(max_retries):
|
|
||||||
last_number = get_max_ticket_number()
|
|
||||||
next_number = last_number + 1
|
|
||||||
try:
|
|
||||||
create_ticket(next_number)
|
|
||||||
break
|
|
||||||
except DuplicateKeyError:
|
|
||||||
if attempt < max_retries - 1:
|
|
||||||
continue # Reintentar
|
|
||||||
```
|
|
||||||
|
|
||||||
**Resultado**:
|
|
||||||
- ✅ 0% fallos por duplicados
|
|
||||||
- ✅ Manejo robusto de alta concurrencia
|
|
||||||
- ✅ Recuperación automática de errores
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## ✨ Mejoras de Código
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
|
|
||||||
1. **Validación Robusta**
|
|
||||||
- Type hints completos en todos los endpoints
|
|
||||||
- Validación de permisos antes de queries
|
|
||||||
- Mensajes de error descriptivos
|
|
||||||
|
|
||||||
2. **Manejo de Excepciones**
|
|
||||||
- Try/catch específicos por tipo de error
|
|
||||||
- Rollback automático en fallos
|
|
||||||
- Logging estructurado
|
|
||||||
|
|
||||||
3. **Documentación**
|
|
||||||
- Docstrings actualizados con información de permisos
|
|
||||||
- Comentarios explicativos en lógica compleja
|
|
||||||
- Ejemplos de uso en código
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
|
|
||||||
1. **API Client**
|
|
||||||
- Header `X-Tenant-ID` en todas las peticiones
|
|
||||||
- Manejo consistente de errores
|
|
||||||
- Type safety mejorado
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📚 Documentación
|
|
||||||
|
|
||||||
### Archivos Nuevos
|
|
||||||
|
|
||||||
1. **CHANGELOG.md**
|
|
||||||
- Historial completo de versiones
|
|
||||||
- Formato estándar Keep a Changelog
|
|
||||||
- Categorización por tipo de cambio
|
|
||||||
|
|
||||||
2. **test_rbac.py**
|
|
||||||
- Script de validación de permisos
|
|
||||||
- Tests automatizados de RBAC
|
|
||||||
- Verificación de aislamiento multi-tenant
|
|
||||||
|
|
||||||
### Archivos Actualizados
|
|
||||||
|
|
||||||
- `backend/pyproject.toml` → v1.5.1
|
|
||||||
- `frontend-internal/package.json` → v1.5.1
|
|
||||||
- `frontend-client/package.json` → v1.5.1
|
|
||||||
- Endpoints: tickets.py, categories.py, systems.py
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🧪 Testing
|
|
||||||
|
|
||||||
### Scripts de Validación
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Test de control de acceso
|
|
||||||
python backend/test_rbac.py
|
|
||||||
|
|
||||||
# Test de creación de tickets
|
|
||||||
python backend/test_ticket_numbers.py
|
|
||||||
|
|
||||||
# Verificar usuarios y roles
|
|
||||||
python backend/list_all_users.py
|
|
||||||
```
|
|
||||||
|
|
||||||
### Cobertura
|
|
||||||
|
|
||||||
- ✅ RBAC implementado y validado
|
|
||||||
- ✅ Multi-tenancy verificado
|
|
||||||
- ✅ Generación de números probada
|
|
||||||
- ✅ Endpoints protegidos confirmados
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 💾 Backup
|
|
||||||
|
|
||||||
**Ubicación**: `../backups/ServiceManagerWeb_v1.5.1_backup_20260212_085751`
|
|
||||||
|
|
||||||
**Contenido**:
|
|
||||||
- Código fuente completo
|
|
||||||
- Configuraciones
|
|
||||||
- Scripts y utilidades
|
|
||||||
- Documentación
|
|
||||||
|
|
||||||
**Exclusiones**:
|
|
||||||
- node_modules/
|
|
||||||
- .git/
|
|
||||||
- __pycache__/
|
|
||||||
- logs/
|
|
||||||
- uploads/
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🚀 Despliegue
|
|
||||||
|
|
||||||
### Para Subir al Repositorio Remoto
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Subir commit
|
|
||||||
git push origin main
|
|
||||||
|
|
||||||
# Subir tag
|
|
||||||
git push origin v1.5.1
|
|
||||||
```
|
|
||||||
|
|
||||||
### Para Desplegar en Producción
|
|
||||||
|
|
||||||
1. Pull de la versión
|
|
||||||
```bash
|
|
||||||
git fetch --tags
|
|
||||||
git checkout v1.5.1
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Actualizar dependencias
|
|
||||||
```bash
|
|
||||||
docker-compose pull
|
|
||||||
docker-compose build
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Reiniciar servicios
|
|
||||||
```bash
|
|
||||||
docker-compose down
|
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
4. Verificar estado
|
|
||||||
```bash
|
|
||||||
docker-compose ps
|
|
||||||
curl http://localhost:8000/health
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## ⚠️ Breaking Changes
|
|
||||||
|
|
||||||
**Ninguno**: Esta versión es completamente compatible con v1.4.x
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📊 Estadísticas
|
|
||||||
|
|
||||||
- **Archivos modificados**: 8
|
|
||||||
- **Líneas agregadas**: 336
|
|
||||||
- **Líneas eliminadas**: 101
|
|
||||||
- **Commits**: 1
|
|
||||||
- **Tags**: 1
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 👥 Contribuidores
|
|
||||||
|
|
||||||
- **Autor**: icamarillo <icamarillo@aduanasoft.com.mx>
|
|
||||||
- **Fecha**: Thu Feb 12 09:00:16 2026 -0700
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🔗 Referencias
|
|
||||||
|
|
||||||
- **Commit**: 771b6eba30e183fafbff6d2f074a41c378170730
|
|
||||||
- **Tag**: v1.5.1
|
|
||||||
- **Rama**: main
|
|
||||||
- **Changelog**: CHANGELOG.md
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
_Generado automáticamente el 12 de Febrero, 2026_
|
|
||||||
@@ -51,6 +51,55 @@ class AuditLogResponse(AuditLogBase):
|
|||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# ===================================
|
||||||
|
# SECURITY ANALYSIS SCHEMAS
|
||||||
|
# ===================================
|
||||||
|
|
||||||
|
class SecurityThreatPattern(BaseModel):
|
||||||
|
"""Patrón de amenaza detectado."""
|
||||||
|
type: str = Field(description="Tipo de amenaza (brute_force, privilege_escalation, etc.)")
|
||||||
|
severity: str = Field(description="Severidad: low, medium, high, critical")
|
||||||
|
description: str = Field(description="Descripción de la amenaza")
|
||||||
|
occurrences: int = Field(description="Número de ocurrencias")
|
||||||
|
affected_ips: list[str] = Field(default=[], description="IPs involucradas")
|
||||||
|
affected_users: list[str] = Field(default=[], description="Usuarios afectados")
|
||||||
|
first_seen: datetime = Field(description="Primera ocurrencia")
|
||||||
|
last_seen: datetime = Field(description="Última ocurrencia")
|
||||||
|
recommendations: list[str] = Field(default=[], description="Recomendaciones de acción")
|
||||||
|
|
||||||
|
|
||||||
|
class SecurityAnalysisResponse(BaseModel):
|
||||||
|
"""Análisis completo de seguridad."""
|
||||||
|
overall_risk_level: str = Field(description="Nivel de riesgo general: safe, low, medium, high, critical")
|
||||||
|
total_threats_detected: int = Field(description="Total de amenazas detectadas")
|
||||||
|
threats: list[SecurityThreatPattern] = Field(description="Lista de amenazas detectadas")
|
||||||
|
analysis_period_hours: int = Field(description="Período de análisis en horas")
|
||||||
|
generated_at: datetime = Field(description="Timestamp del análisis")
|
||||||
|
|
||||||
|
# Estadísticas de seguridad
|
||||||
|
failed_login_attempts: int = Field(description="Intentos fallidos de login")
|
||||||
|
suspicious_ips_count: int = Field(description="IPs sospechosas detectadas")
|
||||||
|
critical_actions_count: int = Field(description="Acciones críticas realizadas")
|
||||||
|
|
||||||
|
# Opciones de acción
|
||||||
|
recommended_actions: list[str] = Field(default=[], description="Acciones recomendadas")
|
||||||
|
|
||||||
|
|
||||||
|
class SecurityActionRequest(BaseModel):
|
||||||
|
"""Solicitud de acción de seguridad."""
|
||||||
|
action_type: str = Field(description="Tipo de acción: block_ip, notify_admin, reset_password, etc.")
|
||||||
|
target: str = Field(description="Objetivo de la acción (IP, email, etc.)")
|
||||||
|
reason: str = Field(description="Razón de la acción")
|
||||||
|
duration_minutes: Optional[int] = Field(None, description="Duración del bloqueo en minutos")
|
||||||
|
|
||||||
|
|
||||||
|
class SecurityActionResponse(BaseModel):
|
||||||
|
"""Respuesta de acción de seguridad."""
|
||||||
|
success: bool = Field(description="Si la acción fue exitosa")
|
||||||
|
message: str = Field(description="Mensaje descriptivo")
|
||||||
|
action_id: Optional[UUID4] = Field(None, description="ID de la acción registrada")
|
||||||
|
|
||||||
|
|
||||||
class AuditLogFilters(BaseModel):
|
class AuditLogFilters(BaseModel):
|
||||||
"""
|
"""
|
||||||
Filtros para consulta de audit logs.
|
Filtros para consulta de audit logs.
|
||||||
@@ -84,6 +133,7 @@ class AuditLogStats(BaseModel):
|
|||||||
total_actions: int = Field(description="Total de acciones registradas")
|
total_actions: int = Field(description="Total de acciones registradas")
|
||||||
actions_today: int = Field(description="Acciones en las ├║ltimas 24 horas")
|
actions_today: int = Field(description="Acciones en las ├║ltimas 24 horas")
|
||||||
actions_this_week: int = Field(description="Acciones en los últimos 7 días")
|
actions_this_week: int = Field(description="Acciones en los últimos 7 días")
|
||||||
|
critical_actions_today: int = Field(description="Acciones críticas hoy (delete, cambios sensibles)")
|
||||||
|
|
||||||
# Top acciones
|
# Top acciones
|
||||||
top_actions: Dict[str, int] = Field(description="Acciones más frecuentes")
|
top_actions: Dict[str, int] = Field(description="Acciones más frecuentes")
|
||||||
|
|||||||
@@ -133,10 +133,10 @@ class ClientProfileUpdate(ClientProfileBase):
|
|||||||
class ClientProfileResponse(ClientProfileBase):
|
class ClientProfileResponse(ClientProfileBase):
|
||||||
"""Schema de respuesta para ClientProfile."""
|
"""Schema de respuesta para ClientProfile."""
|
||||||
|
|
||||||
id: Optional[uuid.UUID] = None
|
id: uuid.UUID
|
||||||
tenant_id: uuid.UUID
|
tenant_id: uuid.UUID
|
||||||
created_at: Optional[datetime] = None
|
created_at: datetime
|
||||||
updated_at: Optional[datetime] = None
|
updated_at: datetime
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|||||||
@@ -19,11 +19,16 @@ from app.api.deps import get_current_user, get_current_tenant
|
|||||||
from app.models.user import User, UserRole
|
from app.models.user import User, UserRole
|
||||||
from app.models.tenant import Tenant
|
from app.models.tenant import Tenant
|
||||||
from app.models.audit import AuditLog
|
from app.models.audit import AuditLog
|
||||||
|
from app.services.audit_service import AuditService
|
||||||
from app.api.schemas.audit import (
|
from app.api.schemas.audit import (
|
||||||
AuditLogResponse,
|
AuditLogResponse,
|
||||||
AuditLogListResponse,
|
AuditLogListResponse,
|
||||||
AuditLogFilters,
|
AuditLogFilters,
|
||||||
AuditLogStats
|
AuditLogStats,
|
||||||
|
SecurityAnalysisResponse,
|
||||||
|
SecurityThreatPattern,
|
||||||
|
SecurityActionRequest,
|
||||||
|
SecurityActionResponse
|
||||||
)
|
)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -61,8 +66,10 @@ async def get_audit_logs(
|
|||||||
date_from: Optional[datetime] = Query(None, description="Fecha desde"),
|
date_from: Optional[datetime] = Query(None, description="Fecha desde"),
|
||||||
date_to: Optional[datetime] = Query(None, description="Fecha hasta"),
|
date_to: Optional[datetime] = Query(None, description="Fecha hasta"),
|
||||||
search: Optional[str] = Query(None, description="B├║squeda en acci├│n o email"),
|
search: Optional[str] = Query(None, description="B├║squeda en acci├│n o email"),
|
||||||
|
# Multi-tenant filters (solo ADMIN/SUPPORT_MANAGER)
|
||||||
# Dependencies
|
tenant_id: Optional[uuid.UUID] = Query(None, description="Ver logs de un tenant específico"),
|
||||||
|
all_tenants: bool = Query(False, description="Ver logs de todos los tenants"),
|
||||||
|
# Dependencies
|
||||||
current_user: User = Depends(require_auditor_role),
|
current_user: User = Depends(require_auditor_role),
|
||||||
current_tenant: Tenant = Depends(get_current_tenant),
|
current_tenant: Tenant = Depends(get_current_tenant),
|
||||||
db: AsyncSession = Depends(get_db)
|
db: AsyncSession = Depends(get_db)
|
||||||
@@ -90,17 +97,28 @@ async def get_audit_logs(
|
|||||||
"user_id": str(user_id) if user_id else None,
|
"user_id": str(user_id) if user_id else None,
|
||||||
"action": action,
|
"action": action,
|
||||||
"resource_type": resource_type,
|
"resource_type": resource_type,
|
||||||
"page": page
|
"page": page,
|
||||||
|
"tenant_filter": str(tenant_id) if tenant_id else None,
|
||||||
|
"all_tenants": all_tenants
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
# Query base - solo logs del tenant actual
|
# Determinar el filtro de tenant
|
||||||
# Usar selectinload para cargar la relaci├│n user (eager loading para async)
|
# Solo ADMIN y SUPPORT_MANAGER pueden ver otros tenants o todos los tenants
|
||||||
query = (
|
can_see_all_tenants = current_user.role in [UserRole.ADMIN, UserRole.SUPPORT_MANAGER]
|
||||||
select(AuditLog)
|
|
||||||
.where(AuditLog.tenant_id == current_tenant.id)
|
# Query base con filtro de tenant dinámico
|
||||||
.options(selectinload(AuditLog.user))
|
query = select(AuditLog).options(selectinload(AuditLog.user))
|
||||||
)
|
|
||||||
|
if all_tenants and can_see_all_tenants:
|
||||||
|
# Ver todos los tenants (no agregar filtro de tenant)
|
||||||
|
pass
|
||||||
|
elif tenant_id and can_see_all_tenants:
|
||||||
|
# Ver un tenant específico
|
||||||
|
query = query.where(AuditLog.tenant_id == tenant_id)
|
||||||
|
else:
|
||||||
|
# Ver solo el tenant actual (comportamiento default)
|
||||||
|
query = query.where(AuditLog.tenant_id == current_tenant.id)
|
||||||
|
|
||||||
# Aplicar filtros
|
# Aplicar filtros
|
||||||
if user_id:
|
if user_id:
|
||||||
@@ -119,9 +137,8 @@ async def get_audit_logs(
|
|||||||
query = query.where(AuditLog.created_at >= date_from)
|
query = query.where(AuditLog.created_at >= date_from)
|
||||||
|
|
||||||
if date_to:
|
if date_to:
|
||||||
# Agregar 1 día para incluir todo el día
|
# El frontend ya envía el timestamp correcto
|
||||||
date_to_end = date_to + timedelta(days=1)
|
query = query.where(AuditLog.created_at < date_to)
|
||||||
query = query.where(AuditLog.created_at < date_to_end)
|
|
||||||
|
|
||||||
if search:
|
if search:
|
||||||
# B├║squeda en action
|
# B├║squeda en action
|
||||||
@@ -188,51 +205,57 @@ async def get_audit_logs(
|
|||||||
|
|
||||||
@router.get("/stats", response_model=AuditLogStats)
|
@router.get("/stats", response_model=AuditLogStats)
|
||||||
async def get_audit_stats(
|
async def get_audit_stats(
|
||||||
|
all_tenants: bool = Query(False, description="Ver stats de todos los tenants"),
|
||||||
current_user: User = Depends(require_auditor_role),
|
current_user: User = Depends(require_auditor_role),
|
||||||
current_tenant: Tenant = Depends(get_current_tenant),
|
current_tenant: Tenant = Depends(get_current_tenant),
|
||||||
db: AsyncSession = Depends(get_db)
|
db: AsyncSession = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Obtener estadísticas de auditoría del tenant.
|
Obtener estadísticas de auditoría del tenant (o todos los tenants si es ADMIN).
|
||||||
|
|
||||||
**Permisos**: ADMIN, SUPPORT_MANAGER, AUDITOR
|
**Permisos**: ADMIN, SUPPORT_MANAGER, AUDITOR
|
||||||
|
|
||||||
**Retorna**: Estadísticas de actividad
|
**Retorna**: Estadísticas de actividad
|
||||||
"""
|
"""
|
||||||
|
can_see_all_tenants = current_user.role in [UserRole.ADMIN, UserRole.SUPPORT_MANAGER]
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"Fetching audit stats",
|
"Fetching audit stats",
|
||||||
user_id=str(current_user.id),
|
user_id=str(current_user.id),
|
||||||
tenant_id=str(current_tenant.id)
|
tenant_id=str(current_tenant.id),
|
||||||
|
all_tenants=all_tenants,
|
||||||
|
can_see_all=can_see_all_tenants
|
||||||
)
|
)
|
||||||
|
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
|
|
||||||
|
# Determinar si aplicar filtro de tenant
|
||||||
|
apply_tenant_filter = not (all_tenants and can_see_all_tenants)
|
||||||
|
|
||||||
# Total de acciones
|
# Total de acciones
|
||||||
total_query = select(func.count()).select_from(AuditLog).where(
|
total_query = select(func.count()).select_from(AuditLog)
|
||||||
AuditLog.tenant_id == current_tenant.id
|
if apply_tenant_filter:
|
||||||
)
|
total_query = total_query.where(AuditLog.tenant_id == current_tenant.id)
|
||||||
total_result = await db.execute(total_query)
|
total_result = await db.execute(total_query)
|
||||||
total_actions = total_result.scalar() or 0
|
total_actions = total_result.scalar() or 0
|
||||||
|
|
||||||
# Acciones hoy (├║ltimas 24 horas)
|
# Acciones hoy (├║ltimas 24 horas)
|
||||||
today_start = now - timedelta(days=1)
|
today_start = now - timedelta(days=1)
|
||||||
today_query = select(func.count()).select_from(AuditLog).where(
|
today_query = select(func.count()).select_from(AuditLog).where(
|
||||||
and_(
|
AuditLog.created_at >= today_start
|
||||||
AuditLog.tenant_id == current_tenant.id,
|
|
||||||
AuditLog.created_at >= today_start
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
if apply_tenant_filter:
|
||||||
|
today_query = today_query.where(AuditLog.tenant_id == current_tenant.id)
|
||||||
today_result = await db.execute(today_query)
|
today_result = await db.execute(today_query)
|
||||||
actions_today = today_result.scalar() or 0
|
actions_today = today_result.scalar() or 0
|
||||||
|
|
||||||
# Acciones esta semana (últimos 7 días)
|
# Acciones esta semana (últimos 7 días)
|
||||||
week_start = now - timedelta(days=7)
|
week_start = now - timedelta(days=7)
|
||||||
week_query = select(func.count()).select_from(AuditLog).where(
|
week_query = select(func.count()).select_from(AuditLog).where(
|
||||||
and_(
|
AuditLog.created_at >= week_start
|
||||||
AuditLog.tenant_id == current_tenant.id,
|
|
||||||
AuditLog.created_at >= week_start
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
if apply_tenant_filter:
|
||||||
|
week_query = week_query.where(AuditLog.tenant_id == current_tenant.id)
|
||||||
week_result = await db.execute(week_query)
|
week_result = await db.execute(week_query)
|
||||||
actions_this_week = week_result.scalar() or 0
|
actions_this_week = week_result.scalar() or 0
|
||||||
|
|
||||||
@@ -240,9 +263,10 @@ async def get_audit_stats(
|
|||||||
top_actions_query = select(
|
top_actions_query = select(
|
||||||
AuditLog.action,
|
AuditLog.action,
|
||||||
func.count(AuditLog.id).label('count')
|
func.count(AuditLog.id).label('count')
|
||||||
).where(
|
)
|
||||||
AuditLog.tenant_id == current_tenant.id
|
if apply_tenant_filter:
|
||||||
).group_by(
|
top_actions_query = top_actions_query.where(AuditLog.tenant_id == current_tenant.id)
|
||||||
|
top_actions_query = top_actions_query.group_by(
|
||||||
AuditLog.action
|
AuditLog.action
|
||||||
).order_by(
|
).order_by(
|
||||||
desc('count')
|
desc('count')
|
||||||
@@ -255,9 +279,10 @@ async def get_audit_stats(
|
|||||||
by_resource_query = select(
|
by_resource_query = select(
|
||||||
AuditLog.resource_type,
|
AuditLog.resource_type,
|
||||||
func.count(AuditLog.id).label('count')
|
func.count(AuditLog.id).label('count')
|
||||||
).where(
|
)
|
||||||
AuditLog.tenant_id == current_tenant.id
|
if apply_tenant_filter:
|
||||||
).group_by(
|
by_resource_query = by_resource_query.where(AuditLog.tenant_id == current_tenant.id)
|
||||||
|
by_resource_query = by_resource_query.group_by(
|
||||||
AuditLog.resource_type
|
AuditLog.resource_type
|
||||||
).order_by(
|
).order_by(
|
||||||
desc('count')
|
desc('count')
|
||||||
@@ -266,14 +291,48 @@ async def get_audit_stats(
|
|||||||
by_resource_result = await db.execute(by_resource_query)
|
by_resource_result = await db.execute(by_resource_query)
|
||||||
by_resource_type = {row.resource_type: row.count for row in by_resource_result}
|
by_resource_type = {row.resource_type: row.count for row in by_resource_result}
|
||||||
|
|
||||||
# Top usuarios (necesitamos hacer join - simplificado por ahora)
|
# Top usuarios (con join a users para obtener nombres)
|
||||||
# En producción podrías hacer un join con users para obtener nombres
|
top_users_query = select(
|
||||||
top_users = {} # Placeholder - implementar con join si es necesario
|
User.email,
|
||||||
|
func.count(AuditLog.id).label('count')
|
||||||
|
).join(
|
||||||
|
User, AuditLog.user_id == User.id
|
||||||
|
)
|
||||||
|
if apply_tenant_filter:
|
||||||
|
top_users_query = top_users_query.where(AuditLog.tenant_id == current_tenant.id)
|
||||||
|
top_users_query = top_users_query.group_by(
|
||||||
|
User.email
|
||||||
|
).order_by(
|
||||||
|
desc('count')
|
||||||
|
).limit(5)
|
||||||
|
|
||||||
|
top_users_result = await db.execute(top_users_query)
|
||||||
|
top_users = {row.email: row.count for row in top_users_result}
|
||||||
|
|
||||||
|
# Acciones críticas hoy (delete, update sensibles, etc.)
|
||||||
|
critical_conditions = [
|
||||||
|
AuditLog.created_at >= today_start,
|
||||||
|
or_(
|
||||||
|
AuditLog.action.like('%.delete'),
|
||||||
|
AuditLog.action.like('user.update'),
|
||||||
|
AuditLog.action.like('%.assign'),
|
||||||
|
AuditLog.action.in_(['user.login_failed', 'user.logout'])
|
||||||
|
)
|
||||||
|
]
|
||||||
|
if apply_tenant_filter:
|
||||||
|
critical_conditions.append(AuditLog.tenant_id == current_tenant.id)
|
||||||
|
|
||||||
|
critical_actions_query = select(func.count()).select_from(AuditLog).where(
|
||||||
|
and_(*critical_conditions)
|
||||||
|
)
|
||||||
|
critical_result = await db.execute(critical_actions_query)
|
||||||
|
critical_actions_today = critical_result.scalar() or 0
|
||||||
|
|
||||||
return AuditLogStats(
|
return AuditLogStats(
|
||||||
total_actions=total_actions,
|
total_actions=total_actions,
|
||||||
actions_today=actions_today,
|
actions_today=actions_today,
|
||||||
actions_this_week=actions_this_week,
|
actions_this_week=actions_this_week,
|
||||||
|
critical_actions_today=critical_actions_today,
|
||||||
top_actions=top_actions,
|
top_actions=top_actions,
|
||||||
top_users=top_users,
|
top_users=top_users,
|
||||||
by_resource_type=by_resource_type
|
by_resource_type=by_resource_type
|
||||||
@@ -336,3 +395,321 @@ async def get_audit_log_detail(
|
|||||||
log_dict["user_name"] = log.user.full_name
|
log_dict["user_name"] = log.user.full_name
|
||||||
|
|
||||||
return AuditLogResponse(**log_dict)
|
return AuditLogResponse(**log_dict)
|
||||||
|
|
||||||
|
|
||||||
|
# ===================================
|
||||||
|
# SECURITY ANALYSIS ENDPOINTS
|
||||||
|
# ===================================
|
||||||
|
|
||||||
|
@router.get("/security/analysis", response_model=SecurityAnalysisResponse)
|
||||||
|
async def get_security_analysis(
|
||||||
|
hours: int = Query(default=24, ge=1, le=168, description="Período de análisis en horas"),
|
||||||
|
current_user: User = Depends(require_auditor_role),
|
||||||
|
current_tenant: Tenant = Depends(get_current_tenant),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Análisis de seguridad y detección de amenazas.
|
||||||
|
|
||||||
|
**Permisos**: ADMIN, SUPPORT_MANAGER, AUDITOR
|
||||||
|
|
||||||
|
**Detecta**:
|
||||||
|
- Intentos de fuerza bruta (login_failed)
|
||||||
|
- Escalada de privilegios
|
||||||
|
- Eliminaciones masivas
|
||||||
|
- Accesos desde IPs sospechosas
|
||||||
|
- Patrones anómalos de actividad
|
||||||
|
|
||||||
|
**Retorna**: Análisis completo con amenazas y recomendaciones
|
||||||
|
"""
|
||||||
|
logger.info(
|
||||||
|
"Security analysis requested",
|
||||||
|
user_id=str(current_user.id),
|
||||||
|
tenant_id=str(current_tenant.id),
|
||||||
|
hours=hours
|
||||||
|
)
|
||||||
|
|
||||||
|
now = datetime.utcnow()
|
||||||
|
analysis_start = now - timedelta(hours=hours)
|
||||||
|
|
||||||
|
threats = []
|
||||||
|
failed_login_attempts = 0
|
||||||
|
suspicious_ips = set()
|
||||||
|
critical_actions_count = 0
|
||||||
|
|
||||||
|
# 1. DETECCIÓN DE FUERZA BRUTA
|
||||||
|
brute_force_query = select(
|
||||||
|
AuditLog.ip_address,
|
||||||
|
func.count(AuditLog.id).label('attempts'),
|
||||||
|
func.min(AuditLog.created_at).label('first_seen'),
|
||||||
|
func.max(AuditLog.created_at).label('last_seen')
|
||||||
|
).where(
|
||||||
|
and_(
|
||||||
|
AuditLog.tenant_id == current_tenant.id,
|
||||||
|
AuditLog.action == 'user.login_failed',
|
||||||
|
AuditLog.created_at >= analysis_start
|
||||||
|
)
|
||||||
|
).group_by(AuditLog.ip_address).having(func.count(AuditLog.id) >= 5)
|
||||||
|
|
||||||
|
brute_force_result = await db.execute(brute_force_query)
|
||||||
|
brute_force_ips = brute_force_result.all()
|
||||||
|
|
||||||
|
for ip_data in brute_force_ips:
|
||||||
|
if ip_data.ip_address:
|
||||||
|
suspicious_ips.add(str(ip_data.ip_address))
|
||||||
|
failed_login_attempts += ip_data.attempts
|
||||||
|
|
||||||
|
severity = "high" if ip_data.attempts > 20 else "medium" if ip_data.attempts > 10 else "low"
|
||||||
|
|
||||||
|
threats.append(SecurityThreatPattern(
|
||||||
|
type="brute_force_attack",
|
||||||
|
severity=severity,
|
||||||
|
description=f"Ataque de fuerza bruta detectado desde {ip_data.ip_address}",
|
||||||
|
occurrences=ip_data.attempts,
|
||||||
|
affected_ips=[str(ip_data.ip_address)],
|
||||||
|
affected_users=[],
|
||||||
|
first_seen=ip_data.first_seen,
|
||||||
|
last_seen=ip_data.last_seen,
|
||||||
|
recommendations=[
|
||||||
|
f"Bloquear IP {ip_data.ip_address} temporalmente",
|
||||||
|
"Revisar logs de firewall",
|
||||||
|
"Considerar implementar CAPTCHA",
|
||||||
|
"Notificar al equipo de seguridad"
|
||||||
|
]
|
||||||
|
))
|
||||||
|
|
||||||
|
# 2. ESCALADA DE PRIVILEGIOS
|
||||||
|
privilege_query = select(
|
||||||
|
User.email,
|
||||||
|
func.count(AuditLog.id).label('changes'),
|
||||||
|
func.min(AuditLog.created_at).label('first_seen'),
|
||||||
|
func.max(AuditLog.created_at).label('last_seen')
|
||||||
|
).join(
|
||||||
|
User, AuditLog.user_id == User.id
|
||||||
|
).where(
|
||||||
|
and_(
|
||||||
|
AuditLog.tenant_id == current_tenant.id,
|
||||||
|
AuditLog.action == 'user.update',
|
||||||
|
AuditLog.created_at >= analysis_start,
|
||||||
|
AuditLog.new_values.op('?')('role')
|
||||||
|
)
|
||||||
|
).group_by(User.email).having(func.count(AuditLog.id) >= 3)
|
||||||
|
|
||||||
|
privilege_result = await db.execute(privilege_query)
|
||||||
|
privilege_changes = privilege_result.all()
|
||||||
|
|
||||||
|
for priv_data in privilege_changes:
|
||||||
|
threats.append(SecurityThreatPattern(
|
||||||
|
type="privilege_escalation",
|
||||||
|
severity="critical",
|
||||||
|
description=f"Posible escalada de privilegios - {priv_data.email} ha modificado roles {priv_data.changes} veces",
|
||||||
|
occurrences=priv_data.changes,
|
||||||
|
affected_ips=[],
|
||||||
|
affected_users=[priv_data.email],
|
||||||
|
first_seen=priv_data.first_seen,
|
||||||
|
last_seen=priv_data.last_seen,
|
||||||
|
recommendations=[
|
||||||
|
f"Revisar permisos del usuario {priv_data.email}",
|
||||||
|
"Auditar todos los cambios de roles realizados",
|
||||||
|
"Verificar si los cambios fueron autorizados",
|
||||||
|
"Considerar revertir cambios no autorizados"
|
||||||
|
]
|
||||||
|
))
|
||||||
|
|
||||||
|
# 3. ELIMINACIONES MASIVAS
|
||||||
|
deletion_query = select(
|
||||||
|
User.email,
|
||||||
|
func.count(AuditLog.id).label('deletions'),
|
||||||
|
func.min(AuditLog.created_at).label('first_seen'),
|
||||||
|
func.max(AuditLog.created_at).label('last_seen')
|
||||||
|
).join(
|
||||||
|
User, AuditLog.user_id == User.id
|
||||||
|
).where(
|
||||||
|
and_(
|
||||||
|
AuditLog.tenant_id == current_tenant.id,
|
||||||
|
AuditLog.action.like('%.delete'),
|
||||||
|
AuditLog.created_at >= analysis_start
|
||||||
|
)
|
||||||
|
).group_by(User.email).having(func.count(AuditLog.id) >= 10)
|
||||||
|
|
||||||
|
deletion_result = await db.execute(deletion_query)
|
||||||
|
mass_deletions = deletion_result.all()
|
||||||
|
|
||||||
|
for del_data in mass_deletions:
|
||||||
|
critical_actions_count += del_data.deletions
|
||||||
|
threats.append(SecurityThreatPattern(
|
||||||
|
type="mass_deletion",
|
||||||
|
severity="high",
|
||||||
|
description=f"Eliminaciones masivas detectadas - {del_data.email} ha eliminado {del_data.deletions} recursos",
|
||||||
|
occurrences=del_data.deletions,
|
||||||
|
affected_ips=[],
|
||||||
|
affected_users=[del_data.email],
|
||||||
|
first_seen=del_data.first_seen,
|
||||||
|
last_seen=del_data.last_seen,
|
||||||
|
recommendations=[
|
||||||
|
f"Verificar urgentemente las eliminaciones de {del_data.email}",
|
||||||
|
"Comprobar si hay backups disponibles",
|
||||||
|
"Contactar al usuario para verificar la acción",
|
||||||
|
"Revisar sistema de permisos"
|
||||||
|
]
|
||||||
|
))
|
||||||
|
|
||||||
|
# 4. ACCESOS DESDE MÚLTIPLES IPS (Cuenta comprometida)
|
||||||
|
multi_ip_query = select(
|
||||||
|
User.email,
|
||||||
|
func.count(func.distinct(AuditLog.ip_address)).label('ip_count'),
|
||||||
|
func.min(AuditLog.created_at).label('first_seen'),
|
||||||
|
func.max(AuditLog.created_at).label('last_seen')
|
||||||
|
).join(
|
||||||
|
User, AuditLog.user_id == User.id
|
||||||
|
).where(
|
||||||
|
and_(
|
||||||
|
AuditLog.tenant_id == current_tenant.id,
|
||||||
|
AuditLog.action.in_(['user.login', 'user.logout']),
|
||||||
|
AuditLog.created_at >= analysis_start
|
||||||
|
)
|
||||||
|
).group_by(User.email).having(func.count(func.distinct(AuditLog.ip_address)) >= 5)
|
||||||
|
|
||||||
|
multi_ip_result = await db.execute(multi_ip_query)
|
||||||
|
multi_ip_users = multi_ip_result.all()
|
||||||
|
|
||||||
|
for ip_data in multi_ip_users:
|
||||||
|
threats.append(SecurityThreatPattern(
|
||||||
|
type="account_compromise",
|
||||||
|
severity="medium",
|
||||||
|
description=f"Posible cuenta comprometida - {ip_data.email} accedió desde {ip_data.ip_count} IPs diferentes",
|
||||||
|
occurrences=ip_data.ip_count,
|
||||||
|
affected_ips=[],
|
||||||
|
affected_users=[ip_data.email],
|
||||||
|
first_seen=ip_data.first_seen,
|
||||||
|
last_seen=ip_data.last_seen,
|
||||||
|
recommendations=[
|
||||||
|
f"Contactar a {ip_data.email} para verificar actividad",
|
||||||
|
"Forzar cambio de contraseña",
|
||||||
|
"Revisar ubicaciones de acceso",
|
||||||
|
"Considerar habilitar 2FA obligatorio"
|
||||||
|
]
|
||||||
|
))
|
||||||
|
|
||||||
|
# Calcular nivel de riesgo general
|
||||||
|
critical_count = sum(1 for t in threats if t.severity == "critical")
|
||||||
|
high_count = sum(1 for t in threats if t.severity == "high")
|
||||||
|
medium_count = sum(1 for t in threats if t.severity == "medium")
|
||||||
|
|
||||||
|
if critical_count > 0:
|
||||||
|
overall_risk = "critical"
|
||||||
|
elif high_count >= 3:
|
||||||
|
overall_risk = "high"
|
||||||
|
elif high_count > 0 or medium_count >= 3:
|
||||||
|
overall_risk = "medium"
|
||||||
|
elif medium_count > 0 or len(threats) > 0:
|
||||||
|
overall_risk = "low"
|
||||||
|
else:
|
||||||
|
overall_risk = "safe"
|
||||||
|
|
||||||
|
# Recomendaciones generales
|
||||||
|
recommended_actions = []
|
||||||
|
if failed_login_attempts > 20:
|
||||||
|
recommended_actions.append("Implementar límite de intentos de login por IP")
|
||||||
|
if len(suspicious_ips) > 0:
|
||||||
|
recommended_actions.append(f"Bloquear {len(suspicious_ips)} IPs sospechosas identificadas")
|
||||||
|
if critical_actions_count > 50:
|
||||||
|
recommended_actions.append("Revisar políticas de permisos - demasiadas acciones críticas")
|
||||||
|
if len(threats) == 0:
|
||||||
|
recommended_actions.append("Sistema seguro - continuar monitoreando")
|
||||||
|
|
||||||
|
return SecurityAnalysisResponse(
|
||||||
|
overall_risk_level=overall_risk,
|
||||||
|
total_threats_detected=len(threats),
|
||||||
|
threats=threats,
|
||||||
|
analysis_period_hours=hours,
|
||||||
|
generated_at=now,
|
||||||
|
failed_login_attempts=failed_login_attempts,
|
||||||
|
suspicious_ips_count=len(suspicious_ips),
|
||||||
|
critical_actions_count=critical_actions_count,
|
||||||
|
recommended_actions=recommended_actions
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/security/action", response_model=SecurityActionResponse)
|
||||||
|
async def execute_security_action(
|
||||||
|
action: SecurityActionRequest,
|
||||||
|
current_user: User = Depends(require_auditor_role),
|
||||||
|
current_tenant: Tenant = Depends(get_current_tenant),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Ejecutar acción de seguridad.
|
||||||
|
|
||||||
|
**Permisos**: ADMIN, SUPPORT_MANAGER (solo ellos pueden ejecutar acciones)
|
||||||
|
|
||||||
|
**Acciones disponibles**:
|
||||||
|
- `block_ip`: Bloquear IP temporalmente
|
||||||
|
- `notify_admin`: Notificar administradores
|
||||||
|
- `force_password_reset`: Forzar cambio de contraseña
|
||||||
|
- `disable_user`: Desactivar usuario temporalmente
|
||||||
|
|
||||||
|
**Retorna**: Resultado de la acción
|
||||||
|
"""
|
||||||
|
# Verificar que solo ADMIN y SUPPORT_MANAGER puedan ejecutar acciones
|
||||||
|
if current_user.role not in [UserRole.ADMIN, UserRole.SUPPORT_MANAGER]:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Solo administradores pueden ejecutar acciones de seguridad"
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Security action requested",
|
||||||
|
user_id=str(current_user.id),
|
||||||
|
action_type=action.action_type,
|
||||||
|
target=action.target
|
||||||
|
)
|
||||||
|
|
||||||
|
# Registrar la acción en auditoría
|
||||||
|
try:
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=current_tenant.id,
|
||||||
|
user_id=current_user.id,
|
||||||
|
action=f"security.{action.action_type}",
|
||||||
|
resource_type="security",
|
||||||
|
resource_id=None,
|
||||||
|
metadata={
|
||||||
|
"target": action.target,
|
||||||
|
"reason": action.reason,
|
||||||
|
"duration_minutes": action.duration_minutes
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to log security action", error=str(e))
|
||||||
|
|
||||||
|
# Por ahora, simular la ejecución (en producción conectar con firewall, email, etc.)
|
||||||
|
message = ""
|
||||||
|
success = True
|
||||||
|
|
||||||
|
if action.action_type == "block_ip":
|
||||||
|
message = f"IP {action.target} bloqueada por {action.duration_minutes or 60} minutos. Razón: {action.reason}"
|
||||||
|
# TODO: Integrar con firewall/WAF
|
||||||
|
|
||||||
|
elif action.action_type == "notify_admin":
|
||||||
|
message = f"Notificación enviada a administradores sobre: {action.reason}"
|
||||||
|
# TODO: Enviar email/Slack notification
|
||||||
|
|
||||||
|
elif action.action_type == "force_password_reset":
|
||||||
|
message = f"Se forzará cambio de contraseña para {action.target}. Razón: {action.reason}"
|
||||||
|
# TODO: Marcar usuario para reset password
|
||||||
|
|
||||||
|
elif action.action_type == "disable_user":
|
||||||
|
message = f"Usuario {action.target} desactivado temporalmente. Razón: {action.reason}"
|
||||||
|
# TODO: Desactivar usuario en BD
|
||||||
|
|
||||||
|
else:
|
||||||
|
success = False
|
||||||
|
message = f"Tipo de acción no reconocida: {action.action_type}"
|
||||||
|
|
||||||
|
return SecurityActionResponse(
|
||||||
|
success=success,
|
||||||
|
message=message,
|
||||||
|
action_id=None # TODO: Retornar ID del audit log creado
|
||||||
|
)
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from app.core.security import security
|
|||||||
from app.core.config import get_settings
|
from app.core.config import get_settings
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.models.tenant import Tenant
|
from app.models.tenant import Tenant
|
||||||
|
from app.services.audit_service import AuditService
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
logger = structlog.get_logger(__name__)
|
logger = structlog.get_logger(__name__)
|
||||||
@@ -99,6 +100,23 @@ async def login(
|
|||||||
"Login failed - invalid credentials",
|
"Login failed - invalid credentials",
|
||||||
email=login_data.email
|
email=login_data.email
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Registrar intento fallido en auditoría (si el usuario existe)
|
||||||
|
if user:
|
||||||
|
try:
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=user.tenant_id,
|
||||||
|
user_id=None, # Login fallido = sin user_id
|
||||||
|
action="user.login_failed",
|
||||||
|
resource_type="user",
|
||||||
|
resource_id=user.id,
|
||||||
|
metadata={"email": login_data.email, "reason": "invalid_password"}
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to log audit entry", error=str(e))
|
||||||
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Credenciales inválidas"
|
detail="Credenciales inválidas"
|
||||||
@@ -126,6 +144,21 @@ async def login(
|
|||||||
access_token = security.create_access_token(token_data)
|
access_token = security.create_access_token(token_data)
|
||||||
refresh_token = security.create_refresh_token(token_data)
|
refresh_token = security.create_refresh_token(token_data)
|
||||||
|
|
||||||
|
# Registrar login exitoso en auditoría
|
||||||
|
try:
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=user.tenant_id,
|
||||||
|
user_id=user.id,
|
||||||
|
action="user.login",
|
||||||
|
resource_type="user",
|
||||||
|
resource_id=user.id,
|
||||||
|
metadata={"email": user.email, "success": True}
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to log audit entry", error=str(e))
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"Login successful",
|
"Login successful",
|
||||||
email=login_data.email,
|
email=login_data.email,
|
||||||
@@ -227,6 +260,25 @@ async def logout(
|
|||||||
|
|
||||||
# TODO: Revoke refresh token in database
|
# TODO: Revoke refresh token in database
|
||||||
|
|
||||||
|
# Registrar logout en auditoría
|
||||||
|
try:
|
||||||
|
import uuid
|
||||||
|
user_id = uuid.UUID(payload["sub"])
|
||||||
|
tenant_id = uuid.UUID(payload["tenant_id"])
|
||||||
|
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
user_id=user_id,
|
||||||
|
action="user.logout",
|
||||||
|
resource_type="user",
|
||||||
|
resource_id=user_id,
|
||||||
|
metadata={"email": payload.get("email")}
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to log audit entry", error=str(e))
|
||||||
|
|
||||||
logger.info("Logout successful", user_id=payload["sub"])
|
logger.info("Logout successful", user_id=payload["sub"])
|
||||||
|
|
||||||
return {"message": "Successfully logged out"}
|
return {"message": "Successfully logged out"}
|
||||||
|
|||||||
@@ -82,25 +82,17 @@ async def read_categories(
|
|||||||
async def create_category(
|
async def create_category(
|
||||||
category: CategoryCreate,
|
category: CategoryCreate,
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(deps.get_current_user)
|
current_user: User = Depends(deps.get_current_user) # ✅ CORREGIDO: Type hint
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Crear nueva categoría en el tenant del usuario actual.
|
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.
|
✅ Implementa multi-tenancy: asigna automáticamente tenant_id del usuario.
|
||||||
"""
|
"""
|
||||||
# Verificar permisos
|
# ✅ CORREGIDO: Asignar tenant_id del usuario actual
|
||||||
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(
|
db_category = Category(
|
||||||
**category.model_dump(),
|
**category.model_dump(),
|
||||||
tenant_id=current_user.tenant_id
|
tenant_id=current_user.tenant_id # ✅ Multi-tenancy automático
|
||||||
)
|
)
|
||||||
|
|
||||||
db.add(db_category)
|
db.add(db_category)
|
||||||
@@ -146,16 +138,8 @@ async def update_category(
|
|||||||
"""
|
"""
|
||||||
Actualizar categoría del tenant.
|
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.
|
✅ 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(
|
query = select(Category).where(
|
||||||
Category.id == category_id,
|
Category.id == category_id,
|
||||||
Category.tenant_id == current_user.tenant_id
|
Category.tenant_id == current_user.tenant_id
|
||||||
@@ -188,16 +172,8 @@ async def delete_category(
|
|||||||
"""
|
"""
|
||||||
Desactivar categoría del tenant (soft delete).
|
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.
|
✅ 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(
|
query = select(Category).where(
|
||||||
Category.id == category_id,
|
Category.id == category_id,
|
||||||
Category.tenant_id == current_user.tenant_id
|
Category.tenant_id == current_user.tenant_id
|
||||||
|
|||||||
@@ -50,49 +50,11 @@ async def get_current_client_profile(
|
|||||||
profile = result.scalar_one_or_none()
|
profile = result.scalar_one_or_none()
|
||||||
|
|
||||||
if not profile:
|
if not profile:
|
||||||
# Si no existe, devolver un perfil vacío con solo tenant_id
|
# Si no existe, crear uno vacío
|
||||||
# No crear en base de datos hasta que el usuario guarde
|
profile = ClientProfile(tenant_id=current_tenant.id)
|
||||||
return ClientProfileResponse(
|
db.add(profile)
|
||||||
id=None,
|
await db.commit()
|
||||||
tenant_id=current_tenant.id,
|
await db.refresh(profile)
|
||||||
business_name=None,
|
|
||||||
commercial_name=None,
|
|
||||||
client_code=None,
|
|
||||||
client_type=None,
|
|
||||||
rfc=None,
|
|
||||||
tax_id=None,
|
|
||||||
country=None,
|
|
||||||
state=None,
|
|
||||||
city=None,
|
|
||||||
address=None,
|
|
||||||
external_number=None,
|
|
||||||
internal_number=None,
|
|
||||||
postal_code=None,
|
|
||||||
neighborhood=None,
|
|
||||||
main_phone=None,
|
|
||||||
secondary_phone=None,
|
|
||||||
direct_phone=None,
|
|
||||||
phone_extension=None,
|
|
||||||
fax=None,
|
|
||||||
business_hours=None,
|
|
||||||
website=None,
|
|
||||||
main_email=None,
|
|
||||||
billing_email=None,
|
|
||||||
advertising_medium=None,
|
|
||||||
nationality=None,
|
|
||||||
logo_url=None,
|
|
||||||
company_representative=None,
|
|
||||||
legal_representative=None,
|
|
||||||
credit_limit=None,
|
|
||||||
payment_terms=None,
|
|
||||||
preferred_currency="MXN",
|
|
||||||
send_to_billing=False,
|
|
||||||
is_active_client=True,
|
|
||||||
is_prospect=False,
|
|
||||||
notes=None,
|
|
||||||
created_at=None,
|
|
||||||
updated_at=None
|
|
||||||
)
|
|
||||||
|
|
||||||
return profile
|
return profile
|
||||||
|
|
||||||
|
|||||||
@@ -70,25 +70,17 @@ async def read_systems(
|
|||||||
async def create_system(
|
async def create_system(
|
||||||
system: SystemCreate,
|
system: SystemCreate,
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(deps.get_current_user)
|
current_user: User = Depends(deps.get_current_user) # ✅ CORREGIDO: Type hint
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Crear nuevo sistema en el tenant del usuario actual.
|
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.
|
✅ Implementa multi-tenancy: asigna automáticamente tenant_id del usuario.
|
||||||
"""
|
"""
|
||||||
# Verificar permisos
|
# ✅ CORREGIDO: Asignar tenant_id del usuario actual
|
||||||
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(
|
db_system = System(
|
||||||
**system.model_dump(),
|
**system.model_dump(),
|
||||||
tenant_id=current_user.tenant_id
|
tenant_id=current_user.tenant_id # ✅ Multi-tenancy automático
|
||||||
)
|
)
|
||||||
|
|
||||||
db.add(db_system)
|
db.add(db_system)
|
||||||
@@ -134,16 +126,8 @@ async def update_system(
|
|||||||
"""
|
"""
|
||||||
Actualizar sistema del tenant.
|
Actualizar sistema del tenant.
|
||||||
|
|
||||||
**Permisos**: Solo ADMIN y SUPPORT_MANAGER pueden actualizar sistemas.
|
|
||||||
✅ Implementa multi-tenancy: solo permite actualizar sistemas del propio tenant.
|
✅ 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(
|
query = select(System).where(
|
||||||
System.id == system_id,
|
System.id == system_id,
|
||||||
System.tenant_id == current_user.tenant_id
|
System.tenant_id == current_user.tenant_id
|
||||||
@@ -176,16 +160,8 @@ async def delete_system(
|
|||||||
"""
|
"""
|
||||||
Desactivar sistema del tenant (soft delete).
|
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.
|
✅ 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(
|
query = select(System).where(
|
||||||
System.id == system_id,
|
System.id == system_id,
|
||||||
System.tenant_id == current_user.tenant_id
|
System.tenant_id == current_user.tenant_id
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from app.models.comment import TicketComment
|
|||||||
from app.models.attachment import TicketAttachment
|
from app.models.attachment import TicketAttachment
|
||||||
from app.api.schemas.attachment import AttachmentResponse
|
from app.api.schemas.attachment import AttachmentResponse
|
||||||
from app.core.file_handler import file_handler
|
from app.core.file_handler import file_handler
|
||||||
|
from app.services.audit_service import AuditService
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -143,6 +144,27 @@ async def create_ticket(
|
|||||||
await db.commit()
|
await db.commit()
|
||||||
await db.refresh(db_ticket)
|
await db.refresh(db_ticket)
|
||||||
|
|
||||||
|
# Registrar creación en auditoría
|
||||||
|
try:
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=current_user.tenant_id,
|
||||||
|
user_id=current_user.id,
|
||||||
|
action="ticket.create",
|
||||||
|
resource_type="ticket",
|
||||||
|
resource_id=db_ticket.id,
|
||||||
|
new_values={
|
||||||
|
"ticket_number": db_ticket.ticket_number,
|
||||||
|
"subject": db_ticket.subject,
|
||||||
|
"priority": db_ticket.priority.value,
|
||||||
|
"status": db_ticket.status.value
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
# No fallar si falla el audit log
|
||||||
|
pass
|
||||||
|
|
||||||
# ✅ Éxito - retornar ticket creado
|
# ✅ Éxito - retornar ticket creado
|
||||||
return {
|
return {
|
||||||
"id": str(db_ticket.id),
|
"id": str(db_ticket.id),
|
||||||
@@ -501,6 +523,15 @@ async def update_ticket(
|
|||||||
detail=f"Ticket {ticket_id} not found"
|
detail=f"Ticket {ticket_id} not found"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Guardar valores anteriores para audit
|
||||||
|
old_values = {
|
||||||
|
"subject": db_ticket.subject,
|
||||||
|
"description": db_ticket.description,
|
||||||
|
"status": db_ticket.status.value,
|
||||||
|
"priority": db_ticket.priority.value,
|
||||||
|
"assigned_to": str(db_ticket.assigned_to) if db_ticket.assigned_to else None
|
||||||
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
update_data = ticket_update.dict(exclude_unset=True)
|
update_data = ticket_update.dict(exclude_unset=True)
|
||||||
|
|
||||||
@@ -519,6 +550,34 @@ async def update_ticket(
|
|||||||
await db.commit()
|
await db.commit()
|
||||||
await db.refresh(db_ticket)
|
await db.refresh(db_ticket)
|
||||||
|
|
||||||
|
# Registrar actualización en auditoría
|
||||||
|
try:
|
||||||
|
new_values = {
|
||||||
|
"subject": db_ticket.subject,
|
||||||
|
"description": db_ticket.description,
|
||||||
|
"status": db_ticket.status.value,
|
||||||
|
"priority": db_ticket.priority.value,
|
||||||
|
"assigned_to": str(db_ticket.assigned_to) if db_ticket.assigned_to else None
|
||||||
|
}
|
||||||
|
|
||||||
|
# Si cambió assigned_to, registrar como acción de asignación
|
||||||
|
action = "ticket.assign" if old_values["assigned_to"] != new_values["assigned_to"] else "ticket.update"
|
||||||
|
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=current_user.tenant_id,
|
||||||
|
user_id=current_user.id,
|
||||||
|
action=action,
|
||||||
|
resource_type="ticket",
|
||||||
|
resource_id=db_ticket.id,
|
||||||
|
old_values=old_values,
|
||||||
|
new_values=new_values
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
# No fallar si falla el audit log
|
||||||
|
pass
|
||||||
|
|
||||||
# ✅ CORREGIDO: Usar affected_system_id
|
# ✅ CORREGIDO: Usar affected_system_id
|
||||||
return {
|
return {
|
||||||
"id": str(db_ticket.id),
|
"id": str(db_ticket.id),
|
||||||
@@ -787,9 +846,33 @@ async def delete_ticket(
|
|||||||
detail=f"Ticket {ticket_id} not found"
|
detail=f"Ticket {ticket_id} not found"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Guardar datos del ticket antes de eliminar para audit
|
||||||
|
old_values = {
|
||||||
|
"ticket_number": db_ticket.ticket_number,
|
||||||
|
"subject": db_ticket.subject,
|
||||||
|
"status": db_ticket.status.value,
|
||||||
|
"priority": db_ticket.priority.value
|
||||||
|
}
|
||||||
|
|
||||||
await db.delete(db_ticket)
|
await db.delete(db_ticket)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
|
|
||||||
|
# Registrar eliminación en auditoría
|
||||||
|
try:
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=current_user.tenant_id,
|
||||||
|
user_id=current_user.id,
|
||||||
|
action="ticket.delete",
|
||||||
|
resource_type="ticket",
|
||||||
|
resource_id=ticket_uuid,
|
||||||
|
old_values=old_values
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
# No fallar si falla el audit log
|
||||||
|
pass
|
||||||
|
|
||||||
return {"message": "Ticket deleted successfully"}
|
return {"message": "Ticket deleted successfully"}
|
||||||
|
|
||||||
# ===================================
|
# ===================================
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import uuid
|
|||||||
from app.core.database import get_db
|
from app.core.database import get_db
|
||||||
from app.core.security import security
|
from app.core.security import security
|
||||||
from app.models.user import User, UserRole
|
from app.models.user import User, UserRole
|
||||||
|
from app.services.audit_service import AuditService
|
||||||
from app.api import deps
|
from app.api import deps
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -147,6 +148,28 @@ async def create_user(
|
|||||||
db.add(db_user)
|
db.add(db_user)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
await db.refresh(db_user)
|
await db.refresh(db_user)
|
||||||
|
|
||||||
|
# Registrar creación en auditoría
|
||||||
|
try:
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=current_user.tenant_id,
|
||||||
|
user_id=current_user.id,
|
||||||
|
action="user.create",
|
||||||
|
resource_type="user",
|
||||||
|
resource_id=db_user.id,
|
||||||
|
new_values=AuditService.sanitize_values({
|
||||||
|
"email": db_user.email,
|
||||||
|
"first_name": db_user.first_name,
|
||||||
|
"last_name": db_user.last_name,
|
||||||
|
"role": db_user.role.value
|
||||||
|
})
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
# No fallar si falla el audit log
|
||||||
|
pass
|
||||||
|
|
||||||
return db_user
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
@@ -214,6 +237,15 @@ async def update_user(
|
|||||||
detail="User not found"
|
detail="User not found"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Guardar valores anteriores para audit
|
||||||
|
old_values = {
|
||||||
|
"email": db_user.email,
|
||||||
|
"first_name": db_user.first_name,
|
||||||
|
"last_name": db_user.last_name,
|
||||||
|
"role": db_user.role.value,
|
||||||
|
"is_active": db_user.is_active
|
||||||
|
}
|
||||||
|
|
||||||
# Verificar email único si se está cambiando
|
# Verificar email único si se está cambiando
|
||||||
update_data = user_update.model_dump(exclude_unset=True)
|
update_data = user_update.model_dump(exclude_unset=True)
|
||||||
if "email" in update_data and update_data["email"] != db_user.email:
|
if "email" in update_data and update_data["email"] != db_user.email:
|
||||||
@@ -239,6 +271,32 @@ async def update_user(
|
|||||||
|
|
||||||
await db.commit()
|
await db.commit()
|
||||||
await db.refresh(db_user)
|
await db.refresh(db_user)
|
||||||
|
|
||||||
|
# Registrar actualización en auditoría
|
||||||
|
try:
|
||||||
|
new_values = {
|
||||||
|
"email": db_user.email,
|
||||||
|
"first_name": db_user.first_name,
|
||||||
|
"last_name": db_user.last_name,
|
||||||
|
"role": db_user.role.value,
|
||||||
|
"is_active": db_user.is_active
|
||||||
|
}
|
||||||
|
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=current_user.tenant_id,
|
||||||
|
user_id=current_user.id,
|
||||||
|
action="user.update",
|
||||||
|
resource_type="user",
|
||||||
|
resource_id=db_user.id,
|
||||||
|
old_values=AuditService.sanitize_values(old_values),
|
||||||
|
new_values=AuditService.sanitize_values(new_values)
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
# No fallar si falla el audit log
|
||||||
|
pass
|
||||||
|
|
||||||
return db_user
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
@@ -306,6 +364,28 @@ async def delete_user(
|
|||||||
# Soft delete
|
# Soft delete
|
||||||
db_user.is_active = False
|
db_user.is_active = False
|
||||||
await db.commit()
|
await db.commit()
|
||||||
|
|
||||||
|
# Registrar eliminación en auditoría
|
||||||
|
try:
|
||||||
|
await AuditService.log(
|
||||||
|
db=db,
|
||||||
|
tenant_id=current_user.tenant_id,
|
||||||
|
user_id=current_user.id,
|
||||||
|
action="user.delete",
|
||||||
|
resource_type="user",
|
||||||
|
resource_id=db_user.id,
|
||||||
|
old_values={
|
||||||
|
"email": db_user.email,
|
||||||
|
"role": db_user.role.value,
|
||||||
|
"was_active": True
|
||||||
|
},
|
||||||
|
metadata={"action_type": "soft_delete"}
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
# No fallar si falla el audit log
|
||||||
|
pass
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ class Settings(BaseSettings):
|
|||||||
DEBUG: bool = Field(default=False)
|
DEBUG: bool = Field(default=False)
|
||||||
SECRET_KEY: str = Field(...)
|
SECRET_KEY: str = Field(...)
|
||||||
API_VERSION: str = Field(default="v1")
|
API_VERSION: str = Field(default="v1")
|
||||||
|
APP_VERSION: str = Field(default="1.6.0")
|
||||||
|
|
||||||
# ===================================
|
# ===================================
|
||||||
# DATABASE
|
# DATABASE
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ async def lifespan(app: FastAPI):
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="ServiceManagerWeb API",
|
title="ServiceManagerWeb API",
|
||||||
description="Mesa de Ayuda B2B multi-tenant para Aduanasoft",
|
description="Mesa de Ayuda B2B multi-tenant para Aduanasoft",
|
||||||
version=settings.API_VERSION,
|
version=settings.APP_VERSION,
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
docs_url=f"/{settings.API_VERSION}/docs" if settings.ENVIRONMENT == "development" else None,
|
docs_url=f"/{settings.API_VERSION}/docs" if settings.ENVIRONMENT == "development" else None,
|
||||||
redoc_url=f"/{settings.API_VERSION}/redoc" if settings.ENVIRONMENT == "development" else None,
|
redoc_url=f"/{settings.API_VERSION}/redoc" if settings.ENVIRONMENT == "development" else None,
|
||||||
@@ -163,7 +163,8 @@ async def health_check():
|
|||||||
return {
|
return {
|
||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"service": "ServiceManagerWeb API",
|
"service": "ServiceManagerWeb API",
|
||||||
"version": settings.API_VERSION,
|
"version": settings.APP_VERSION,
|
||||||
|
"api_version": settings.API_VERSION,
|
||||||
"environment": settings.ENVIRONMENT
|
"environment": settings.ENVIRONMENT
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,7 +175,8 @@ async def root():
|
|||||||
"""Endpoint raíz con información básica."""
|
"""Endpoint raíz con información básica."""
|
||||||
return {
|
return {
|
||||||
"service": "ServiceManagerWeb API",
|
"service": "ServiceManagerWeb API",
|
||||||
"version": settings.API_VERSION,
|
"version": settings.APP_VERSION,
|
||||||
|
"api_version": settings.API_VERSION,
|
||||||
"docs": f"/{settings.API_VERSION}/docs",
|
"docs": f"/{settings.API_VERSION}/docs",
|
||||||
"environment": settings.ENVIRONMENT
|
"environment": settings.ENVIRONMENT
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,17 @@ class TenantMiddleware(BaseHTTPMiddleware):
|
|||||||
EXCLUDED_PATHS = {
|
EXCLUDED_PATHS = {
|
||||||
"/health",
|
"/health",
|
||||||
"/",
|
"/",
|
||||||
|
"/api/v1/auth/login",
|
||||||
"/v1/auth/login",
|
"/v1/auth/login",
|
||||||
"/docs",
|
"/docs",
|
||||||
|
"/api/v1/docs",
|
||||||
|
"/v1/docs",
|
||||||
"/openapi.json",
|
"/openapi.json",
|
||||||
"/redoc"
|
"/api/v1/openapi.json",
|
||||||
|
"/v1/openapi.json",
|
||||||
|
"/redoc",
|
||||||
|
"/api/v1/redoc",
|
||||||
|
"/v1/redoc"
|
||||||
}
|
}
|
||||||
|
|
||||||
async def dispatch(self, request: Request, call_next) -> Response:
|
async def dispatch(self, request: Request, call_next) -> Response:
|
||||||
|
|||||||
67
backend/create_test_user.py
Normal file
67
backend/create_test_user.py
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
"""
|
||||||
|
Script para crear/actualizar usuario de prueba con contraseña conocida
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
from sqlalchemy import select, update
|
||||||
|
from app.core.database import AsyncSessionLocal
|
||||||
|
from app.core.security import security
|
||||||
|
from app.models.user import User, UserRole
|
||||||
|
from app.models.tenant import Tenant
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
async def create_test_user():
|
||||||
|
async with AsyncSessionLocal() as db:
|
||||||
|
# Buscar tenant
|
||||||
|
tenant_query = select(Tenant).where(Tenant.slug.like('%aduanasoft%')).limit(1)
|
||||||
|
result = await db.execute(tenant_query)
|
||||||
|
tenant = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not tenant:
|
||||||
|
print("❌ No se encontró tenant")
|
||||||
|
return
|
||||||
|
|
||||||
|
print(f"✅ Tenant encontrado: {tenant.name} ({tenant.slug})")
|
||||||
|
|
||||||
|
# Buscar o crear usuario admin
|
||||||
|
user_query = select(User).where(
|
||||||
|
User.email == "admin@aduanasoft.com",
|
||||||
|
User.tenant_id == tenant.id
|
||||||
|
)
|
||||||
|
result = await db.execute(user_query)
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
# Hash de la contraseña "admin123"
|
||||||
|
password_hash = security.hash_password("admin123")
|
||||||
|
|
||||||
|
if user:
|
||||||
|
# Actualizar contraseña
|
||||||
|
user.password_hash = password_hash
|
||||||
|
user.is_active = True
|
||||||
|
user.email_verified = True
|
||||||
|
await db.commit()
|
||||||
|
print(f"✅ Usuario actualizado: {user.email}")
|
||||||
|
else:
|
||||||
|
# Crear usuario nuevo
|
||||||
|
user = User(
|
||||||
|
id=uuid.uuid4(),
|
||||||
|
tenant_id=tenant.id,
|
||||||
|
email="admin@aduanasoft.com",
|
||||||
|
first_name="Admin",
|
||||||
|
last_name="Sistema",
|
||||||
|
password_hash=password_hash,
|
||||||
|
role=UserRole.ADMIN,
|
||||||
|
is_active=True,
|
||||||
|
email_verified=True
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
await db.commit()
|
||||||
|
print(f"✅ Usuario creado: {user.email}")
|
||||||
|
|
||||||
|
print(f"\n📋 Credenciales de prueba:")
|
||||||
|
print(f" Email: admin@aduanasoft.com")
|
||||||
|
print(f" Password: admin123")
|
||||||
|
print(f" Tenant: {tenant.slug}")
|
||||||
|
print(f" Role: ADMIN")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(create_test_user())
|
||||||
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "servicemanager-backend"
|
name = "servicemanager-backend"
|
||||||
version = "1.5.1.2"
|
version = "1.6.0"
|
||||||
description = "ServiceManagerWeb Backend - Mesa de Ayuda B2B"
|
description = "ServiceManagerWeb Backend - Mesa de Ayuda B2B"
|
||||||
authors = [
|
authors = [
|
||||||
{name = "Aduanasoft", email = "dev@aduanasoft.com"}
|
{name = "Aduanasoft", email = "dev@aduanasoft.com"}
|
||||||
|
|||||||
0
backend/set_test_password.py
Normal file
0
backend/set_test_password.py
Normal file
@@ -1,109 +0,0 @@
|
|||||||
"""
|
|
||||||
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())
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
"""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())
|
|
||||||
@@ -369,10 +369,14 @@ CREATE TABLE audit_logs (
|
|||||||
CREATE INDEX idx_audit_logs_tenant_id ON audit_logs(tenant_id);
|
CREATE INDEX idx_audit_logs_tenant_id ON audit_logs(tenant_id);
|
||||||
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id);
|
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id);
|
||||||
CREATE INDEX idx_audit_logs_action ON audit_logs(action);
|
CREATE INDEX idx_audit_logs_action ON audit_logs(action);
|
||||||
CREATE INDEX idx_audit_logs_resource ON audit_logs(resource_type, resource_id);
|
|
||||||
CREATE INDEX idx_audit_logs_correlation_id ON audit_logs(correlation_id);
|
CREATE INDEX idx_audit_logs_correlation_id ON audit_logs(correlation_id);
|
||||||
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at);
|
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at);
|
||||||
|
|
||||||
|
-- Índices compuestos para queries comunes de auditoría
|
||||||
|
CREATE INDEX idx_audit_logs_tenant_action ON audit_logs(tenant_id, action);
|
||||||
|
CREATE INDEX idx_audit_logs_resource ON audit_logs(resource_type, resource_id);
|
||||||
|
CREATE INDEX idx_audit_logs_user_created ON audit_logs(user_id, created_at);
|
||||||
|
|
||||||
-- ===================================
|
-- ===================================
|
||||||
-- FUNCIONES Y TRIGGERS
|
-- FUNCIONES Y TRIGGERS
|
||||||
-- ===================================
|
-- ===================================
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@servicemanager/client-frontend",
|
"name": "@servicemanager/client-frontend",
|
||||||
"version": "1.5.1.2",
|
"version": "1.6.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -23,6 +23,11 @@
|
|||||||
<slot />
|
<slot />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<!-- Footer with version -->
|
||||||
|
<footer class="py-4 text-center border-t border-gray-200 bg-white">
|
||||||
|
<p class="text-xs text-gray-400">ServiceManagerWeb v1.6.0 · © 2026 Aduanasoft</p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
<!-- Toast notifications -->
|
<!-- Toast notifications -->
|
||||||
{#each $toast.toasts as toastMessage (toastMessage.id)}
|
{#each $toast.toasts as toastMessage (toastMessage.id)}
|
||||||
<Toast
|
<Toast
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ export default defineConfig({
|
|||||||
host: '0.0.0.0',
|
host: '0.0.0.0',
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api': {
|
'/api': {
|
||||||
target: 'http://backend:8000',
|
target: 'http://servicemanager-backend:8000',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
rewrite: (path) => path.replace(/^\/api/, '')
|
rewrite: (path) => path.replace(/^\/api/, '')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@servicemanager/internal-frontend",
|
"name": "@servicemanager/internal-frontend",
|
||||||
"version": "1.5.1.2",
|
"version": "1.6.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { auth } from '$lib/stores/auth.js';
|
import { auth } from '$lib/stores/auth.js';
|
||||||
|
;
|
||||||
|
|
||||||
export let toggleSidebar: () => void;
|
export let toggleSidebar: () => void;
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
<script>
|
<script>
|
||||||
import { createEventDispatcher, onMount, onDestroy } from 'svelte';
|
import { createEventDispatcher } from 'svelte';
|
||||||
|
|
||||||
export let open = false;
|
export let open = false;
|
||||||
export let title = '';
|
export let title = '';
|
||||||
|
export let size = 'lg'; // sm, md, lg, xl, 2xl
|
||||||
|
|
||||||
const dispatch = createEventDispatcher();
|
const dispatch = createEventDispatcher();
|
||||||
|
|
||||||
@@ -15,6 +16,20 @@
|
|||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleBackdropClick(e) {
|
||||||
|
if (e.target === e.currentTarget) {
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizeClasses = {
|
||||||
|
sm: 'sm:max-w-sm',
|
||||||
|
md: 'sm:max-w-md',
|
||||||
|
lg: 'sm:max-w-lg',
|
||||||
|
xl: 'sm:max-w-xl',
|
||||||
|
'2xl': 'sm:max-w-2xl'
|
||||||
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:window on:keydown={handleKeydown}/>
|
<svelte:window on:keydown={handleKeydown}/>
|
||||||
@@ -23,21 +38,45 @@
|
|||||||
<div class="fixed inset-0 z-50 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
|
<div class="fixed inset-0 z-50 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
|
||||||
<div class="flex items-end justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
|
<div class="flex items-end justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
|
||||||
|
|
||||||
<div class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75" aria-hidden="true" on:click={close}></div>
|
<!-- Backdrop -->
|
||||||
|
<div
|
||||||
|
class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
|
||||||
|
aria-hidden="true"
|
||||||
|
on:click={handleBackdropClick}
|
||||||
|
></div>
|
||||||
|
|
||||||
|
<!-- Center trick -->
|
||||||
<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">​</span>
|
<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">​</span>
|
||||||
|
|
||||||
<div class="inline-block px-4 pt-5 pb-4 overflow-hidden text-left align-bottom transition-all transform bg-white rounded-lg shadow-xl sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
|
<!-- Modal panel -->
|
||||||
<div class="sm:flex sm:items-start">
|
<div class="inline-block w-full align-bottom bg-white rounded-lg shadow-xl transform transition-all sm:my-8 sm:align-middle {sizeClasses[size]} sm:w-full">
|
||||||
<div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
|
<!-- Header -->
|
||||||
<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
|
<div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
|
||||||
{title}
|
<h3 class="text-lg font-semibold text-gray-900" id="modal-title">
|
||||||
</h3>
|
{title}
|
||||||
<div class="mt-2 text-sm text-gray-500">
|
</h3>
|
||||||
<slot />
|
<button
|
||||||
</div>
|
type="button"
|
||||||
</div>
|
on:click={close}
|
||||||
|
class="text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-500 rounded-lg p-1"
|
||||||
|
>
|
||||||
|
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Body -->
|
||||||
|
<div class="px-6 py-4 max-h-[70vh] overflow-y-auto">
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Footer (optional) -->
|
||||||
|
{#if $$slots.footer}
|
||||||
|
<div class="px-6 py-4 bg-gray-50 border-t border-gray-200 rounded-b-lg">
|
||||||
|
<slot name="footer" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -62,6 +62,11 @@
|
|||||||
name: 'Auditoría',
|
name: 'Auditoría',
|
||||||
href: '/audit',
|
href: '/audit',
|
||||||
icon: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z'
|
icon: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Seguridad',
|
||||||
|
href: '/audit/security',
|
||||||
|
icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z'
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -178,5 +183,10 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Version info -->
|
||||||
|
<div class="px-4 py-2 border-t border-gray-100">
|
||||||
|
<p class="text-xs text-gray-400 text-center">v1.6.0</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -25,15 +25,11 @@ async function request<T>(endpoint: string, options: RequestOptions = {}): Promi
|
|||||||
|
|
||||||
const authState = get(auth);
|
const authState = get(auth);
|
||||||
const token = authState.token || (typeof window !== 'undefined' ? localStorage.getItem('internal_auth_token') : null);
|
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);
|
const headers = new Headers(init.headers);
|
||||||
if (token) {
|
if (token) {
|
||||||
headers.set('Authorization', `Bearer ${token}`);
|
headers.set('Authorization', `Bearer ${token}`);
|
||||||
}
|
}
|
||||||
if (user && user.tenant_id) {
|
|
||||||
headers.set('X-Tenant-ID', user.tenant_id);
|
|
||||||
}
|
|
||||||
if (!headers.has('Content-Type')) {
|
if (!headers.has('Content-Type')) {
|
||||||
headers.set('Content-Type', 'application/json');
|
headers.set('Content-Type', 'application/json');
|
||||||
}
|
}
|
||||||
@@ -69,15 +65,11 @@ async function request<T>(endpoint: string, options: RequestOptions = {}): Promi
|
|||||||
async function downloadFile(endpoint: string, filename: string): Promise<void> {
|
async function downloadFile(endpoint: string, filename: string): Promise<void> {
|
||||||
const authState = get(auth);
|
const authState = get(auth);
|
||||||
const token = authState.token || (typeof window !== 'undefined' ? localStorage.getItem('internal_auth_token') : null);
|
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();
|
const headers = new Headers();
|
||||||
if (token) {
|
if (token) {
|
||||||
headers.set('Authorization', `Bearer ${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}`, {
|
const response = await fetch(`${API_BASE}${endpoint}`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
532
frontend-internal/src/routes/audit/security/+page.svelte
Normal file
532
frontend-internal/src/routes/audit/security/+page.svelte
Normal file
@@ -0,0 +1,532 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { api } from '$lib/utils/api';
|
||||||
|
import { toast } from '$lib/stores/toast';
|
||||||
|
import { auth } from '$lib/stores/auth';
|
||||||
|
import Modal from '$lib/components/Modal.svelte';
|
||||||
|
|
||||||
|
// Estado
|
||||||
|
let isLoading = false;
|
||||||
|
let analysis = null;
|
||||||
|
let analysisHours = 24;
|
||||||
|
let selectedThreat = null;
|
||||||
|
let showActionModal = false;
|
||||||
|
let actionType = '';
|
||||||
|
let actionTarget = '';
|
||||||
|
let actionReason = '';
|
||||||
|
let actionDuration = 60;
|
||||||
|
|
||||||
|
// Usuario actual
|
||||||
|
$: currentUser = $auth.user;
|
||||||
|
$: canExecuteActions = currentUser && (currentUser.role === 'ADMIN' || currentUser.role === 'SUPPORT_MANAGER');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cargar análisis de seguridad
|
||||||
|
*/
|
||||||
|
async function loadSecurityAnalysis() {
|
||||||
|
isLoading = true;
|
||||||
|
try {
|
||||||
|
analysis = await api.get('/audit/security/analysis', { hours: analysisHours });
|
||||||
|
console.log('Security analysis loaded:', analysis);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast.error('Error cargando análisis de seguridad: ' + (e.message || 'Error desconocido'));
|
||||||
|
} finally {
|
||||||
|
isLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cambiar período de análisis
|
||||||
|
*/
|
||||||
|
function changeAnalysisPeriod(hours: number) {
|
||||||
|
analysisHours = hours;
|
||||||
|
loadSecurityAnalysis();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtener color según nivel de riesgo
|
||||||
|
*/
|
||||||
|
function getRiskColor(level: string) {
|
||||||
|
const colors: any = {
|
||||||
|
safe: 'bg-green-100 text-green-800 border-green-300',
|
||||||
|
low: 'bg-blue-100 text-blue-800 border-blue-300',
|
||||||
|
medium: 'bg-yellow-100 text-yellow-800 border-yellow-300',
|
||||||
|
high: 'bg-orange-100 text-orange-800 border-orange-300',
|
||||||
|
critical: 'bg-red-100 text-red-800 border-red-300'
|
||||||
|
};
|
||||||
|
return colors[level] || colors.low;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtener color de severidad de amenaza
|
||||||
|
*/
|
||||||
|
function getSeverityColor(severity: string) {
|
||||||
|
const colors: any = {
|
||||||
|
low: 'bg-blue-100 text-blue-800',
|
||||||
|
medium: 'bg-yellow-100 text-yellow-800',
|
||||||
|
high: 'bg-orange-100 text-orange-800',
|
||||||
|
critical: 'bg-red-100 text-red-800'
|
||||||
|
};
|
||||||
|
return colors[severity] || colors.low;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtener icono de tipo de amenaza
|
||||||
|
*/
|
||||||
|
function getThreatIcon(type: string) {
|
||||||
|
const icons: any = {
|
||||||
|
brute_force_attack: 'M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z',
|
||||||
|
privilege_escalation: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z',
|
||||||
|
mass_deletion: 'M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16',
|
||||||
|
account_compromise: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z'
|
||||||
|
};
|
||||||
|
return icons[type] || icons.account_compromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtener texto legible del tipo de amenaza
|
||||||
|
*/
|
||||||
|
function getThreatTypeText(type: string) {
|
||||||
|
const texts: any = {
|
||||||
|
brute_force_attack: 'Ataque de Fuerza Bruta',
|
||||||
|
privilege_escalation: 'Escalada de Privilegios',
|
||||||
|
mass_deletion: 'Eliminación Masiva',
|
||||||
|
account_compromise: 'Cuenta Comprometida'
|
||||||
|
};
|
||||||
|
return texts[type] || type;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abrir modal para acción de seguridad
|
||||||
|
*/
|
||||||
|
function openActionModal(threat: any, action: string) {
|
||||||
|
if (!canExecuteActions) {
|
||||||
|
toast.error('No tienes permisos para ejecutar acciones de seguridad');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectedThreat = threat;
|
||||||
|
actionType = action;
|
||||||
|
|
||||||
|
// Pre-llenar campos según el tipo de acción
|
||||||
|
if (action === 'block_ip' && threat.affected_ips.length > 0) {
|
||||||
|
actionTarget = threat.affected_ips[0];
|
||||||
|
actionReason = `Bloqueo automático: ${threat.description}`;
|
||||||
|
} else if (action === 'force_password_reset' && threat.affected_users.length > 0) {
|
||||||
|
actionTarget = threat.affected_users[0];
|
||||||
|
actionReason = `Reseteo de seguridad: ${threat.description}`;
|
||||||
|
} else {
|
||||||
|
actionTarget = '';
|
||||||
|
actionReason = threat.description;
|
||||||
|
}
|
||||||
|
|
||||||
|
showActionModal = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ejecutar acción de seguridad
|
||||||
|
*/
|
||||||
|
async function executeSecurityAction() {
|
||||||
|
if (!actionTarget || !actionReason) {
|
||||||
|
toast.error('Completa todos los campos requeridos');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await api.post('/audit/security/action', {
|
||||||
|
action_type: actionType,
|
||||||
|
target: actionTarget,
|
||||||
|
reason: actionReason,
|
||||||
|
duration_minutes: actionDuration
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.success) {
|
||||||
|
toast.success(response.message);
|
||||||
|
showActionModal = false;
|
||||||
|
loadSecurityAnalysis(); // Recargar análisis
|
||||||
|
} else {
|
||||||
|
toast.error(response.message);
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
toast.error('Error ejecutando acción: ' + (e.message || 'Error desconocido'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formatear fecha
|
||||||
|
*/
|
||||||
|
function formatDate(dateString: string) {
|
||||||
|
const date = new Date(dateString);
|
||||||
|
return new Intl.DateTimeFormat('es-MX', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
timeZone: 'UTC',
|
||||||
|
timeZoneName: 'short'
|
||||||
|
}).format(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
loadSecurityAnalysis();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
|
||||||
|
<!-- Header -->
|
||||||
|
<div class="mb-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-2xl font-bold text-gray-900 flex items-center gap-2">
|
||||||
|
<svg class="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||||
|
</svg>
|
||||||
|
Análisis de Seguridad
|
||||||
|
</h1>
|
||||||
|
<p class="mt-1 text-sm text-gray-500">
|
||||||
|
Detección de amenazas y análisis de vulnerabilidades
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
on:click={() => loadSecurityAnalysis()}
|
||||||
|
class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||||
|
</svg>
|
||||||
|
Actualizar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Selector de Período -->
|
||||||
|
<div class="bg-white shadow rounded-lg p-4 mb-6">
|
||||||
|
<div class="flex items-center gap-2 mb-2">
|
||||||
|
<svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||||
|
</svg>
|
||||||
|
<span class="text-sm font-medium text-gray-700">Período de Análisis</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
on:click={() => changeAnalysisPeriod(24)}
|
||||||
|
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors {analysisHours === 24 ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}"
|
||||||
|
>
|
||||||
|
Últimas 24 horas
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
on:click={() => changeAnalysisPeriod(48)}
|
||||||
|
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors {analysisHours === 48 ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}"
|
||||||
|
>
|
||||||
|
Últimas 48 horas
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
on:click={() => changeAnalysisPeriod(168)}
|
||||||
|
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors {analysisHours === 168 ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}"
|
||||||
|
>
|
||||||
|
Última semana
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if isLoading}
|
||||||
|
<div class="flex justify-center items-center py-12">
|
||||||
|
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
|
||||||
|
</div>
|
||||||
|
{:else if analysis}
|
||||||
|
<!-- Resumen de Riesgo -->
|
||||||
|
<div class="bg-white shadow rounded-lg p-6 mb-6 border-l-4 {getRiskColor(analysis.overall_risk_level)}">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900">Nivel de Riesgo General</h3>
|
||||||
|
<p class="text-sm text-gray-600 mt-1">Análisis de {analysis.analysis_period_hours} horas</p>
|
||||||
|
</div>
|
||||||
|
<div class="text-right">
|
||||||
|
<span class="inline-block px-4 py-2 text-2xl font-bold rounded-lg {getRiskColor(analysis.overall_risk_level)}">
|
||||||
|
{analysis.overall_risk_level.toUpperCase()}
|
||||||
|
</span>
|
||||||
|
<p class="text-xs text-gray-500 mt-1">Generado: {formatDate(analysis.generated_at)}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Estadísticas Rápidas -->
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
|
||||||
|
<div class="bg-white rounded-lg shadow p-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-500">Amenazas Detectadas</p>
|
||||||
|
<p class="text-2xl font-bold text-red-600">{analysis.total_threats_detected}</p>
|
||||||
|
</div>
|
||||||
|
<svg class="w-10 h-10 text-red-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bg-white rounded-lg shadow p-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-500">Intentos Fallidos</p>
|
||||||
|
<p class="text-2xl font-bold text-orange-600">{analysis.failed_login_attempts}</p>
|
||||||
|
</div>
|
||||||
|
<svg class="w-10 h-10 text-orange-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bg-white rounded-lg shadow p-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-500">IPs Sospechosas</p>
|
||||||
|
<p class="text-2xl font-bold text-purple-600">{analysis.suspicious_ips_count}</p>
|
||||||
|
</div>
|
||||||
|
<svg class="w-10 h-10 text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bg-white rounded-lg shadow p-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm text-gray-500">Acciones Críticas</p>
|
||||||
|
<p class="text-2xl font-bold text-amber-600">{analysis.critical_actions_count}</p>
|
||||||
|
</div>
|
||||||
|
<svg class="w-10 h-10 text-amber-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Recomendaciones Generales -->
|
||||||
|
{#if analysis.recommended_actions && analysis.recommended_actions.length > 0}
|
||||||
|
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
<svg class="w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||||
|
</svg>
|
||||||
|
<div class="flex-1">
|
||||||
|
<h4 class="text-sm font-semibold text-blue-900 mb-2">Acciones Recomendadas</h4>
|
||||||
|
<ul class="space-y-1">
|
||||||
|
{#each analysis.recommended_actions as action}
|
||||||
|
<li class="text-sm text-blue-800 flex items-start gap-2">
|
||||||
|
<svg class="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
|
||||||
|
</svg>
|
||||||
|
{action}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Lista de Amenazas -->
|
||||||
|
{#if analysis.threats && analysis.threats.length > 0}
|
||||||
|
<div class="space-y-4">
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900">Amenazas Detectadas</h3>
|
||||||
|
|
||||||
|
{#each analysis.threats as threat}
|
||||||
|
<div class="bg-white shadow rounded-lg p-6 border-l-4 {threat.severity === 'critical' ? 'border-red-500' : threat.severity === 'high' ? 'border-orange-500' : threat.severity === 'medium' ? 'border-yellow-500' : 'border-blue-500'}">
|
||||||
|
<!-- Header de Amenaza -->
|
||||||
|
<div class="flex items-start justify-between mb-4">
|
||||||
|
<div class="flex items-start gap-3 flex-1">
|
||||||
|
<div class="p-2 rounded-lg {threat.severity === 'critical' ? 'bg-red-100' : threat.severity === 'high' ? 'bg-orange-100' : threat.severity === 'medium' ? 'bg-yellow-100' : 'bg-blue-100'}">
|
||||||
|
<svg class="w-6 h-6 {threat.severity === 'critical' ? 'text-red-600' : threat.severity === 'high' ? 'text-orange-600' : threat.severity === 'medium' ? 'text-yellow-600' : 'text-blue-600'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d={getThreatIcon(threat.type)} />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1">
|
||||||
|
<div class="flex items-center gap-2 mb-1">
|
||||||
|
<h4 class="text-lg font-semibold text-gray-900">{getThreatTypeText(threat.type)}</h4>
|
||||||
|
<span class="px-2 py-1 text-xs font-semibold rounded-full {getSeverityColor(threat.severity)}">
|
||||||
|
{threat.severity.toUpperCase()}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p class="text-sm text-gray-700">{threat.description}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Detalles -->
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<span class="font-medium text-gray-600">Ocurrencias:</span>
|
||||||
|
<span class="ml-2 text-gray-900 font-semibold">{threat.occurrences}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span class="font-medium text-gray-600">Primera detección:</span>
|
||||||
|
<span class="ml-2 text-gray-900">{formatDate(threat.first_seen)}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span class="font-medium text-gray-600">Última detección:</span>
|
||||||
|
<span class="ml-2 text-gray-900">{formatDate(threat.last_seen)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- IPs y Usuarios Afectados -->
|
||||||
|
{#if threat.affected_ips.length > 0 || threat.affected_users.length > 0}
|
||||||
|
<div class="mb-4 text-sm">
|
||||||
|
{#if threat.affected_ips.length > 0}
|
||||||
|
<div class="mb-2">
|
||||||
|
<span class="font-medium text-gray-600">IPs involucradas:</span>
|
||||||
|
<div class="mt-1 flex flex-wrap gap-1">
|
||||||
|
{#each threat.affected_ips as ip}
|
||||||
|
<code class="px-2 py-1 bg-gray-100 rounded text-xs font-mono">{ip}</code>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if threat.affected_users.length > 0}
|
||||||
|
<div>
|
||||||
|
<span class="font-medium text-gray-600">Usuarios afectados:</span>
|
||||||
|
<div class="mt-1 flex flex-wrap gap-1">
|
||||||
|
{#each threat.affected_users as user}
|
||||||
|
<span class="px-2 py-1 bg-gray-100 rounded text-xs">{user}</span>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Recomendaciones -->
|
||||||
|
{#if threat.recommendations && threat.recommendations.length > 0}
|
||||||
|
<div class="bg-gray-50 rounded-lg p-3 mb-4">
|
||||||
|
<p class="text-xs font-semibold text-gray-700 mb-2">Recomendaciones:</p>
|
||||||
|
<ul class="space-y-1">
|
||||||
|
{#each threat.recommendations as rec}
|
||||||
|
<li class="text-xs text-gray-600 flex items-start gap-2">
|
||||||
|
<svg class="w-3 h-3 text-gray-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
|
||||||
|
</svg>
|
||||||
|
{rec}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Acciones -->
|
||||||
|
{#if canExecuteActions}
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
{#if threat.affected_ips.length > 0}
|
||||||
|
<button
|
||||||
|
on:click={() => openActionModal(threat, 'block_ip')}
|
||||||
|
class="px-3 py-1.5 bg-red-600 text-white text-sm rounded hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
|
||||||
|
</svg>
|
||||||
|
Bloquear IP
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
{#if threat.affected_users.length > 0}
|
||||||
|
<button
|
||||||
|
on:click={() => openActionModal(threat, 'force_password_reset')}
|
||||||
|
class="px-3 py-1.5 bg-orange-600 text-white text-sm rounded hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-orange-500 flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
|
||||||
|
</svg>
|
||||||
|
Resetear Contraseña
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
<button
|
||||||
|
on:click={() => openActionModal(threat, 'notify_admin')}
|
||||||
|
class="px-3 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
|
||||||
|
</svg>
|
||||||
|
Notificar Admin
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<!-- No hay amenazas -->
|
||||||
|
<div class="bg-green-50 border border-green-200 rounded-lg p-8 text-center">
|
||||||
|
<svg class="w-16 h-16 text-green-600 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
|
||||||
|
</svg>
|
||||||
|
<h3 class="text-lg font-semibold text-green-900 mb-2">Sistema Seguro</h3>
|
||||||
|
<p class="text-sm text-green-700">No se detectaron amenazas en el período analizado</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Modal de Acción de Seguridad -->
|
||||||
|
{#if showActionModal}
|
||||||
|
<Modal open={showActionModal} size="lg" title="Ejecutar Acción de Seguridad" on:close={() => showActionModal = false}>
|
||||||
|
<div class="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">Tipo de Acción</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
bind:value={actionType}
|
||||||
|
readonly
|
||||||
|
class="block w-full rounded-md border-gray-300 bg-gray-50 shadow-sm sm:text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Objetivo {#if actionType === 'block_ip'}(IP){:else if actionType === 'force_password_reset'}(Email){/if}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
bind:value={actionTarget}
|
||||||
|
placeholder="IP o email del usuario"
|
||||||
|
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">Razón</label>
|
||||||
|
<textarea
|
||||||
|
bind:value={actionReason}
|
||||||
|
rows="3"
|
||||||
|
placeholder="Razón de la acción de seguridad"
|
||||||
|
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
|
||||||
|
></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if actionType === 'block_ip'}
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">Duración del Bloqueo (minutos)</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
bind:value={actionDuration}
|
||||||
|
min="1"
|
||||||
|
max="10080"
|
||||||
|
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="flex justify-end gap-3 pt-4 border-t">
|
||||||
|
<button
|
||||||
|
on:click={() => showActionModal = false}
|
||||||
|
class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-primary-500"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
on:click={executeSecurityAction}
|
||||||
|
class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
>
|
||||||
|
Ejecutar Acción
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
{/if}
|
||||||
@@ -9,7 +9,6 @@
|
|||||||
let categories = [];
|
let categories = [];
|
||||||
let systems = [];
|
let systems = [];
|
||||||
let users = [];
|
let users = [];
|
||||||
let tenants = []; // Nueva lista de tenants
|
|
||||||
let isLoading = false;
|
let isLoading = false;
|
||||||
let showModal = false;
|
let showModal = false;
|
||||||
let showEditModal = false;
|
let showEditModal = false;
|
||||||
@@ -19,15 +18,6 @@
|
|||||||
// Filtros
|
// Filtros
|
||||||
let filterStatus = '';
|
let filterStatus = '';
|
||||||
let filterPriority = '';
|
let filterPriority = '';
|
||||||
let filterTenant = ''; // Nuevo filtro por cliente/tenant
|
|
||||||
let filterCategory = ''; // Filtro por categoría
|
|
||||||
let filterAssignedTo = ''; // Filtro por asignado a
|
|
||||||
let searchText = ''; // Búsqueda por texto
|
|
||||||
let filterDateFrom = ''; // Fecha desde
|
|
||||||
let filterDateTo = ''; // Fecha hasta
|
|
||||||
|
|
||||||
// Estado de filtros
|
|
||||||
$: activeFiltersCount = [filterTenant, filterStatus, filterPriority, filterCategory, filterAssignedTo, searchText, filterDateFrom, filterDateTo].filter(f => f && f.trim()).length;
|
|
||||||
|
|
||||||
// Form para editar
|
// Form para editar
|
||||||
let editFormData = {
|
let editFormData = {
|
||||||
@@ -60,34 +50,25 @@
|
|||||||
{ value: 'URGENT', label: 'Urgente', color: 'red' }
|
{ value: 'URGENT', label: 'Urgente', color: 'red' }
|
||||||
];
|
];
|
||||||
|
|
||||||
// Ajustar la función loadData para usar el endpoint administrativo con filtros
|
// Ajustar la función loadData para asegurar que los filtros se envíen correctamente
|
||||||
async function loadData() {
|
async function loadData() {
|
||||||
isLoading = true;
|
isLoading = true;
|
||||||
try {
|
try {
|
||||||
// Preparar parámetros filtrando valores vacíos
|
const [ticketsData, categoriesData, systemsData, usersData] = await Promise.all([
|
||||||
const ticketParams = {};
|
api.get('/tickets/', {
|
||||||
if (filterStatus) ticketParams.status_filter = filterStatus;
|
params: {
|
||||||
if (filterPriority) ticketParams.priority_filter = filterPriority;
|
status: filterStatus || undefined,
|
||||||
if (filterTenant) ticketParams.tenant_id_filter = filterTenant;
|
priority: filterPriority || undefined
|
||||||
if (filterCategory) ticketParams.category_filter = filterCategory;
|
}
|
||||||
if (filterAssignedTo) ticketParams.assigned_to_filter = filterAssignedTo;
|
}),
|
||||||
if (searchText) ticketParams.search = searchText;
|
|
||||||
if (filterDateFrom) ticketParams.date_from = filterDateFrom;
|
|
||||||
if (filterDateTo) ticketParams.date_to = filterDateTo;
|
|
||||||
|
|
||||||
const [ticketsData, categoriesData, systemsData, usersData, tenantsData] = await Promise.all([
|
|
||||||
// Usar el nuevo endpoint administrativo
|
|
||||||
api.get('/tickets/admin/all', ticketParams),
|
|
||||||
api.get('/categories/'),
|
api.get('/categories/'),
|
||||||
api.get('/systems/'),
|
api.get('/systems/'),
|
||||||
api.get('/users/'),
|
api.get('/users/')
|
||||||
api.get('/tenants/') // Cargar lista de tenants
|
|
||||||
]);
|
]);
|
||||||
tickets = ticketsData;
|
tickets = ticketsData;
|
||||||
categories = categoriesData;
|
categories = categoriesData;
|
||||||
systems = systemsData;
|
systems = systemsData;
|
||||||
users = usersData;
|
users = usersData;
|
||||||
tenants = tenantsData;
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.error('Error cargando datos: ' + (e.message || 'Error desconocido'));
|
toast.error('Error cargando datos: ' + (e.message || 'Error desconocido'));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -99,28 +80,6 @@
|
|||||||
function applyFilters() {
|
function applyFilters() {
|
||||||
loadData();
|
loadData();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Limpiar todos los filtros
|
|
||||||
function clearFilters() {
|
|
||||||
filterStatus = '';
|
|
||||||
filterPriority = '';
|
|
||||||
filterTenant = '';
|
|
||||||
filterCategory = '';
|
|
||||||
filterAssignedTo = '';
|
|
||||||
searchText = '';
|
|
||||||
filterDateFrom = '';
|
|
||||||
filterDateTo = '';
|
|
||||||
applyFilters();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Búsqueda en tiempo real (debounced)
|
|
||||||
let searchTimeout;
|
|
||||||
function handleSearchInput() {
|
|
||||||
clearTimeout(searchTimeout);
|
|
||||||
searchTimeout = setTimeout(() => {
|
|
||||||
applyFilters();
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openCreateModal() {
|
function openCreateModal() {
|
||||||
selectedTicket = null;
|
selectedTicket = null;
|
||||||
@@ -260,31 +219,12 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="px-4 py-8 mx-auto max-w-7xl sm:px-6 lg:px-8">
|
<div class="px-4 py-8 mx-auto max-w-7xl sm:px-6 lg:px-8">
|
||||||
<div class="sm:flex sm:items-center sm:justify-between">
|
<div class="sm:flex sm:items-center">
|
||||||
<div class="sm:flex-auto">
|
<div class="sm:flex-auto">
|
||||||
<h1 class="text-xl font-semibold text-gray-900">Tickets de Soporte</h1>
|
<h1 class="text-xl font-semibold text-gray-900">Tickets de Soporte</h1>
|
||||||
<p class="mt-2 text-sm text-gray-700">
|
<p class="mt-2 text-sm text-gray-700">Gestión de tickets del sistema de mesa de ayuda.</p>
|
||||||
Gestión de tickets del sistema de mesa de ayuda.
|
|
||||||
{#if activeFiltersCount > 0}
|
|
||||||
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 ml-2">
|
|
||||||
{activeFiltersCount} filtro{activeFiltersCount !== 1 ? 's' : ''} activo{activeFiltersCount !== 1 ? 's' : ''}
|
|
||||||
</span>
|
|
||||||
{/if}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none space-x-3">
|
<div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
|
||||||
{#if activeFiltersCount > 0}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
on:click={clearFilters}
|
|
||||||
class="inline-flex items-center justify-center px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50"
|
|
||||||
>
|
|
||||||
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
|
||||||
</svg>
|
|
||||||
Limpiar filtros
|
|
||||||
</button>
|
|
||||||
{/if}
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
on:click={openCreateModal}
|
on:click={openCreateModal}
|
||||||
@@ -295,139 +235,46 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Filtros Avanzados -->
|
<!-- Filtros -->
|
||||||
<div class="mt-6 bg-white shadow sm:rounded-lg">
|
<div class="mt-6 bg-white shadow sm:rounded-lg p-4">
|
||||||
<div class="px-4 py-5 sm:p-6">
|
<div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
<h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">Filtros</h3>
|
<div>
|
||||||
|
<label for="filterStatus" class="block text-sm font-medium text-gray-700">Estado</label>
|
||||||
<!-- Primera fila - Búsqueda y Filtros principales -->
|
<select
|
||||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-4 mb-4">
|
id="filterStatus"
|
||||||
<!-- Búsqueda por texto -->
|
bind:value={filterStatus}
|
||||||
<div class="sm:col-span-2">
|
on:change={applyFilters}
|
||||||
<label for="searchText" class="block text-sm font-medium text-gray-700 mb-1">Búsqueda</label>
|
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm border p-2"
|
||||||
<div class="relative">
|
>
|
||||||
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
<option value="">Todos</option>
|
||||||
<svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
{#each STATUSES as status}
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
<option value={status.value}>{status.label}</option>
|
||||||
</svg>
|
{/each}
|
||||||
</div>
|
</select>
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="searchText"
|
|
||||||
bind:value={searchText}
|
|
||||||
on:input={handleSearchInput}
|
|
||||||
placeholder="Buscar en título o descripción..."
|
|
||||||
class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Cliente/Empresa -->
|
|
||||||
<div>
|
|
||||||
<label for="filterTenant" class="block text-sm font-medium text-gray-700 mb-1">Cliente/Empresa</label>
|
|
||||||
<select
|
|
||||||
id="filterTenant"
|
|
||||||
bind:value={filterTenant}
|
|
||||||
on:change={applyFilters}
|
|
||||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
|
||||||
>
|
|
||||||
<option value="">Todos los clientes</option>
|
|
||||||
{#each tenants as tenant}
|
|
||||||
<option value={tenant.id}>{tenant.name}</option>
|
|
||||||
{/each}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Estado -->
|
|
||||||
<div>
|
|
||||||
<label for="filterStatus" class="block text-sm font-medium text-gray-700 mb-1">Estado</label>
|
|
||||||
<select
|
|
||||||
id="filterStatus"
|
|
||||||
bind:value={filterStatus}
|
|
||||||
on:change={applyFilters}
|
|
||||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
|
||||||
>
|
|
||||||
<option value="">Todos</option>
|
|
||||||
{#each STATUSES as status}
|
|
||||||
<option value={status.value}>{status.label}</option>
|
|
||||||
{/each}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Segunda fila - Filtros secundarios -->
|
<div>
|
||||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-5">
|
<label for="filterPriority" class="block text-sm font-medium text-gray-700">Prioridad</label>
|
||||||
<!-- Prioridad -->
|
<select
|
||||||
<div>
|
id="filterPriority"
|
||||||
<label for="filterPriority" class="block text-sm font-medium text-gray-700 mb-1">Prioridad</label>
|
bind:value={filterPriority}
|
||||||
<select
|
on:change={applyFilters}
|
||||||
id="filterPriority"
|
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm border p-2"
|
||||||
bind:value={filterPriority}
|
>
|
||||||
on:change={applyFilters}
|
<option value="">Todas</option>
|
||||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
{#each PRIORITIES as priority}
|
||||||
>
|
<option value={priority.value}>{priority.label}</option>
|
||||||
<option value="">Todas</option>
|
{/each}
|
||||||
{#each PRIORITIES as priority}
|
</select>
|
||||||
<option value={priority.value}>{priority.label}</option>
|
</div>
|
||||||
{/each}
|
|
||||||
</select>
|
<div class="flex items-end">
|
||||||
</div>
|
<button
|
||||||
|
on:click={loadData}
|
||||||
<!-- Categoría -->
|
class="w-full inline-flex justify-center items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
|
||||||
<div>
|
>
|
||||||
<label for="filterCategory" class="block text-sm font-medium text-gray-700 mb-1">Categoría</label>
|
Actualizar
|
||||||
<select
|
</button>
|
||||||
id="filterCategory"
|
|
||||||
bind:value={filterCategory}
|
|
||||||
on:change={applyFilters}
|
|
||||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
|
||||||
>
|
|
||||||
<option value="">Todas</option>
|
|
||||||
{#each categories as category}
|
|
||||||
<option value={category.id}>{category.name}</option>
|
|
||||||
{/each}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Asignado a -->
|
|
||||||
<div>
|
|
||||||
<label for="filterAssignedTo" class="block text-sm font-medium text-gray-700 mb-1">Asignado a</label>
|
|
||||||
<select
|
|
||||||
id="filterAssignedTo"
|
|
||||||
bind:value={filterAssignedTo}
|
|
||||||
on:change={applyFilters}
|
|
||||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
|
||||||
>
|
|
||||||
<option value="">Todos</option>
|
|
||||||
{#each users.filter(u => u.role === 'AGENT' || u.role === 'SUPPORT_MANAGER' || u.role === 'ADMIN') as user}
|
|
||||||
<option value={user.id}>{user.first_name} {user.last_name}</option>
|
|
||||||
{/each}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Fecha desde -->
|
|
||||||
<div>
|
|
||||||
<label for="filterDateFrom" class="block text-sm font-medium text-gray-700 mb-1">Desde</label>
|
|
||||||
<input
|
|
||||||
type="date"
|
|
||||||
id="filterDateFrom"
|
|
||||||
bind:value={filterDateFrom}
|
|
||||||
on:change={applyFilters}
|
|
||||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Fecha hasta -->
|
|
||||||
<div>
|
|
||||||
<label for="filterDateTo" class="block text-sm font-medium text-gray-700 mb-1">Hasta</label>
|
|
||||||
<input
|
|
||||||
type="date"
|
|
||||||
id="filterDateTo"
|
|
||||||
bind:value={filterDateTo}
|
|
||||||
on:change={applyFilters}
|
|
||||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -441,13 +288,12 @@
|
|||||||
<thead class="bg-gray-50">
|
<thead class="bg-gray-50">
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">Ticket</th>
|
<th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">Ticket</th>
|
||||||
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Cliente/Empresa</th>
|
|
||||||
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Asunto</th>
|
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Asunto</th>
|
||||||
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Estado</th>
|
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Estado</th>
|
||||||
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Prioridad</th>
|
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Prioridad</th>
|
||||||
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Creado por</th>
|
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Categoría</th>
|
||||||
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Asignado a</th>
|
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Asignado a</th>
|
||||||
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Fecha</th>
|
<th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Creado</th>
|
||||||
<th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
|
<th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
|
||||||
<span class="sr-only">Acciones</span>
|
<span class="sr-only">Acciones</span>
|
||||||
</th>
|
</th>
|
||||||
@@ -455,9 +301,9 @@
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody class="divide-y divide-gray-200 bg-white">
|
<tbody class="divide-y divide-gray-200 bg-white">
|
||||||
{#if isLoading}
|
{#if isLoading}
|
||||||
<tr><td colspan="9" class="text-center py-4">Cargando...</td></tr>
|
<tr><td colspan="8" class="text-center py-4">Cargando...</td></tr>
|
||||||
{:else if tickets.length === 0}
|
{:else if tickets.length === 0}
|
||||||
<tr><td colspan="9" class="text-center py-4">No hay tickets registrados</td></tr>
|
<tr><td colspan="8" class="text-center py-4">No hay tickets registrados</td></tr>
|
||||||
{:else}
|
{:else}
|
||||||
{#each tickets as ticket}
|
{#each tickets as ticket}
|
||||||
<tr
|
<tr
|
||||||
@@ -467,10 +313,6 @@
|
|||||||
<td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">
|
<td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">
|
||||||
{ticket.ticket_number || ticket.id.substring(0, 8)}
|
{ticket.ticket_number || ticket.id.substring(0, 8)}
|
||||||
</td>
|
</td>
|
||||||
<td class="px-3 py-4 text-sm text-gray-900">
|
|
||||||
<div class="font-medium text-indigo-600">{ticket.tenant?.name || 'N/A'}</div>
|
|
||||||
<div class="text-xs text-gray-500">{ticket.tenant?.contact_email || ''}</div>
|
|
||||||
</td>
|
|
||||||
<td class="px-3 py-4 text-sm text-gray-900">
|
<td class="px-3 py-4 text-sm text-gray-900">
|
||||||
<div class="font-medium">{ticket.subject}</div>
|
<div class="font-medium">{ticket.subject}</div>
|
||||||
<div class="text-gray-500 truncate max-w-xs">{ticket.description}</div>
|
<div class="text-gray-500 truncate max-w-xs">{ticket.description}</div>
|
||||||
@@ -485,10 +327,8 @@
|
|||||||
{getPriorityBadge(ticket.priority).label}
|
{getPriorityBadge(ticket.priority).label}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td class="px-3 py-4 text-sm text-gray-900">
|
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
|
||||||
<div class="font-medium">{ticket.created_by_user?.first_name} {ticket.created_by_user?.last_name}</div>
|
{getCategoryName(ticket.category_id)}
|
||||||
<div class="text-xs text-gray-500">{ticket.created_by_user?.email}</div>
|
|
||||||
<div class="text-xs text-indigo-600">{ticket.created_by_user?.role || ''}</div>
|
|
||||||
</td>
|
</td>
|
||||||
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
|
<td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
|
||||||
{getUserName(ticket.assigned_to)}
|
{getUserName(ticket.assigned_to)}
|
||||||
|
|||||||
@@ -1,262 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Database Utilities Script
|
|
||||||
Herramientas administrativas para gestión de base de datos
|
|
||||||
|
|
||||||
Uso:
|
|
||||||
python scripts/db_utils.py list-users [--tenant-id UUID]
|
|
||||||
python scripts/db_utils.py check-user EMAIL
|
|
||||||
python scripts/db_utils.py reset-password EMAIL [--password PASSWORD]
|
|
||||||
python scripts/db_utils.py list-tickets [--tenant-id UUID] [--limit N]
|
|
||||||
python scripts/db_utils.py check-ticket TICKET_ID
|
|
||||||
|
|
||||||
Ejemplos:
|
|
||||||
python scripts/db_utils.py list-users
|
|
||||||
python scripts/db_utils.py check-user admin@example.com
|
|
||||||
python scripts/db_utils.py reset-password admin@example.com --password admin123
|
|
||||||
python scripts/db_utils.py list-tickets --limit 10
|
|
||||||
"""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import sys
|
|
||||||
import os
|
|
||||||
from typing import Optional
|
|
||||||
import argparse
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
# Agregar backend al path para imports
|
|
||||||
backend_path = Path(__file__).parent.parent / "backend"
|
|
||||||
sys.path.insert(0, str(backend_path))
|
|
||||||
|
|
||||||
from sqlalchemy import select
|
|
||||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
||||||
from sqlalchemy.orm import sessionmaker
|
|
||||||
|
|
||||||
from app.models.user import User
|
|
||||||
from app.models.ticket import Ticket
|
|
||||||
from app.models.tenant import Tenant
|
|
||||||
from app.core.security import SecurityUtils
|
|
||||||
|
|
||||||
|
|
||||||
class DBUtils:
|
|
||||||
"""Utilidades de gestión de base de datos"""
|
|
||||||
|
|
||||||
def __init__(self, database_url: Optional[str] = None):
|
|
||||||
self.database_url = database_url or os.getenv(
|
|
||||||
'DATABASE_URL',
|
|
||||||
'postgresql+asyncpg://postgres:postgres@localhost:5432/servicemanager'
|
|
||||||
)
|
|
||||||
self.engine = create_async_engine(self.database_url, echo=False)
|
|
||||||
self.async_session = sessionmaker(
|
|
||||||
self.engine,
|
|
||||||
class_=AsyncSession,
|
|
||||||
expire_on_commit=False
|
|
||||||
)
|
|
||||||
|
|
||||||
async def list_users(self, tenant_id: Optional[str] = None):
|
|
||||||
"""Listar todos los usuarios"""
|
|
||||||
async with self.async_session() as session:
|
|
||||||
query = select(User)
|
|
||||||
if tenant_id:
|
|
||||||
query = query.where(User.tenant_id == tenant_id)
|
|
||||||
|
|
||||||
result = await session.execute(query)
|
|
||||||
users = result.scalars().all()
|
|
||||||
|
|
||||||
if not users:
|
|
||||||
print("❌ No se encontraron usuarios")
|
|
||||||
return
|
|
||||||
|
|
||||||
print(f"\n{'='*80}")
|
|
||||||
print(f"📋 USUARIOS ({len(users)} encontrados)")
|
|
||||||
print(f"{'='*80}\n")
|
|
||||||
|
|
||||||
for user in users:
|
|
||||||
print(f" Email: {user.email}")
|
|
||||||
print(f" Role: {user.role}")
|
|
||||||
print(f" ID: {user.id}")
|
|
||||||
print(f" Tenant ID: {user.tenant_id}")
|
|
||||||
print(f" Activo: {'✅' if user.is_active else '❌'}")
|
|
||||||
print(f" {'-'*76}")
|
|
||||||
|
|
||||||
async def check_user(self, email: str):
|
|
||||||
"""Verificar información de un usuario específico"""
|
|
||||||
async with self.async_session() as session:
|
|
||||||
result = await session.execute(
|
|
||||||
select(User).where(User.email == email)
|
|
||||||
)
|
|
||||||
user = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not user:
|
|
||||||
print(f"❌ Usuario '{email}' no encontrado")
|
|
||||||
return
|
|
||||||
|
|
||||||
print(f"\n{'='*80}")
|
|
||||||
print(f"👤 INFORMACIÓN DEL USUARIO")
|
|
||||||
print(f"{'='*80}\n")
|
|
||||||
print(f" Email: {user.email}")
|
|
||||||
print(f" Nombre: {user.first_name} {user.last_name}")
|
|
||||||
print(f" Role: {user.role}")
|
|
||||||
print(f" ID: {user.id}")
|
|
||||||
print(f" Tenant ID: {user.tenant_id}")
|
|
||||||
print(f" Activo: {'✅' if user.is_active else '❌'}")
|
|
||||||
print(f" 2FA: {'✅ Habilitado' if user.totp_secret else '❌ Deshabilitado'}")
|
|
||||||
print(f" Creado: {user.created_at}")
|
|
||||||
print(f"\n{'='*80}")
|
|
||||||
|
|
||||||
async def reset_password(self, email: str, new_password: str = "admin123"):
|
|
||||||
"""Resetear contraseña de un usuario"""
|
|
||||||
async with self.async_session() as session:
|
|
||||||
result = await session.execute(
|
|
||||||
select(User).where(User.email == email)
|
|
||||||
)
|
|
||||||
user = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not user:
|
|
||||||
print(f"❌ Usuario '{email}' no encontrado")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Hash nueva contraseña
|
|
||||||
password_hash = SecurityUtils.hash_password(new_password)
|
|
||||||
user.password_hash = password_hash
|
|
||||||
|
|
||||||
try:
|
|
||||||
await session.commit()
|
|
||||||
print(f"\n✅ Contraseña actualizada exitosamente")
|
|
||||||
print(f" Usuario: {email}")
|
|
||||||
print(f" Nueva contraseña: {new_password}")
|
|
||||||
print(f"\n⚠️ IMPORTANTE: Cambia esta contraseña después del primer login")
|
|
||||||
except Exception as e:
|
|
||||||
await session.rollback()
|
|
||||||
print(f"❌ Error al actualizar contraseña: {e}")
|
|
||||||
|
|
||||||
async def list_tickets(self, tenant_id: Optional[str] = None, limit: int = 20):
|
|
||||||
"""Listar tickets"""
|
|
||||||
async with self.async_session() as session:
|
|
||||||
query = select(Ticket).order_by(Ticket.created_at.desc()).limit(limit)
|
|
||||||
if tenant_id:
|
|
||||||
query = query.where(Ticket.tenant_id == tenant_id)
|
|
||||||
|
|
||||||
result = await session.execute(query)
|
|
||||||
tickets = result.scalars().all()
|
|
||||||
|
|
||||||
if not tickets:
|
|
||||||
print("❌ No se encontraron tickets")
|
|
||||||
return
|
|
||||||
|
|
||||||
print(f"\n{'='*80}")
|
|
||||||
print(f"🎫 TICKETS ({len(tickets)} encontrados, límite: {limit})")
|
|
||||||
print(f"{'='*80}\n")
|
|
||||||
|
|
||||||
for ticket in tickets:
|
|
||||||
print(f" {ticket.ticket_number} | {ticket.status} | {ticket.priority}")
|
|
||||||
print(f" Asunto: {ticket.subject}")
|
|
||||||
print(f" ID: {ticket.id}")
|
|
||||||
print(f" Tenant: {ticket.tenant_id}")
|
|
||||||
print(f" Creado: {ticket.created_at}")
|
|
||||||
print(f" {'-'*76}")
|
|
||||||
|
|
||||||
async def check_ticket(self, ticket_id: str):
|
|
||||||
"""Verificar información de un ticket específico"""
|
|
||||||
async with self.async_session() as session:
|
|
||||||
result = await session.execute(
|
|
||||||
select(Ticket).where(Ticket.id == ticket_id)
|
|
||||||
)
|
|
||||||
ticket = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not ticket:
|
|
||||||
print(f"❌ Ticket '{ticket_id}' no encontrado")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Obtener creador
|
|
||||||
creator_result = await session.execute(
|
|
||||||
select(User).where(User.id == ticket.created_by)
|
|
||||||
)
|
|
||||||
creator = creator_result.scalar_one_or_none()
|
|
||||||
|
|
||||||
# Obtener asignado
|
|
||||||
assigned = None
|
|
||||||
if ticket.assigned_to:
|
|
||||||
assigned_result = await session.execute(
|
|
||||||
select(User).where(User.id == ticket.assigned_to)
|
|
||||||
)
|
|
||||||
assigned = assigned_result.scalar_one_or_none()
|
|
||||||
|
|
||||||
print(f"\n{'='*80}")
|
|
||||||
print(f"🎫 INFORMACIÓN DEL TICKET")
|
|
||||||
print(f"{'='*80}\n")
|
|
||||||
print(f" Número: {ticket.ticket_number}")
|
|
||||||
print(f" Asunto: {ticket.subject}")
|
|
||||||
print(f" Estado: {ticket.status}")
|
|
||||||
print(f" Prioridad: {ticket.priority}")
|
|
||||||
print(f" ID: {ticket.id}")
|
|
||||||
print(f" Tenant ID: {ticket.tenant_id}")
|
|
||||||
if creator:
|
|
||||||
print(f" Creado por: {creator.email} ({creator.role})")
|
|
||||||
if assigned:
|
|
||||||
print(f" Asignado a: {assigned.email} ({assigned.role})")
|
|
||||||
print(f" Creado: {ticket.created_at}")
|
|
||||||
print(f" Actualizado: {ticket.updated_at}")
|
|
||||||
print(f"\n{'='*80}")
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""Cerrar conexión"""
|
|
||||||
await self.engine.dispose()
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description='Utilidades de gestión de base de datos',
|
|
||||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
||||||
epilog=__doc__
|
|
||||||
)
|
|
||||||
|
|
||||||
subparsers = parser.add_subparsers(dest='command', help='Comando a ejecutar')
|
|
||||||
|
|
||||||
# list-users
|
|
||||||
list_users_parser = subparsers.add_parser('list-users', help='Listar usuarios')
|
|
||||||
list_users_parser.add_argument('--tenant-id', help='Filtrar por tenant ID')
|
|
||||||
|
|
||||||
# check-user
|
|
||||||
check_user_parser = subparsers.add_parser('check-user', help='Verificar usuario')
|
|
||||||
check_user_parser.add_argument('email', help='Email del usuario')
|
|
||||||
|
|
||||||
# reset-password
|
|
||||||
reset_password_parser = subparsers.add_parser('reset-password', help='Resetear contraseña')
|
|
||||||
reset_password_parser.add_argument('email', help='Email del usuario')
|
|
||||||
reset_password_parser.add_argument('--password', default='admin123', help='Nueva contraseña')
|
|
||||||
|
|
||||||
# list-tickets
|
|
||||||
list_tickets_parser = subparsers.add_parser('list-tickets', help='Listar tickets')
|
|
||||||
list_tickets_parser.add_argument('--tenant-id', help='Filtrar por tenant ID')
|
|
||||||
list_tickets_parser.add_argument('--limit', type=int, default=20, help='Límite de resultados')
|
|
||||||
|
|
||||||
# check-ticket
|
|
||||||
check_ticket_parser = subparsers.add_parser('check-ticket', help='Verificar ticket')
|
|
||||||
check_ticket_parser.add_argument('ticket_id', help='ID del ticket')
|
|
||||||
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
if not args.command:
|
|
||||||
parser.print_help()
|
|
||||||
return
|
|
||||||
|
|
||||||
utils = DBUtils()
|
|
||||||
|
|
||||||
try:
|
|
||||||
if args.command == 'list-users':
|
|
||||||
await utils.list_users(args.tenant_id)
|
|
||||||
elif args.command == 'check-user':
|
|
||||||
await utils.check_user(args.email)
|
|
||||||
elif args.command == 'reset-password':
|
|
||||||
await utils.reset_password(args.email, args.password)
|
|
||||||
elif args.command == 'list-tickets':
|
|
||||||
await utils.list_tickets(args.tenant_id, args.limit)
|
|
||||||
elif args.command == 'check-ticket':
|
|
||||||
await utils.check_ticket(args.ticket_id)
|
|
||||||
finally:
|
|
||||||
await utils.close()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
Reference in New Issue
Block a user