187 lines
4.9 KiB
Markdown
187 lines
4.9 KiB
Markdown
# ServiceManagerWeb Backend
|
|
|
|
FastAPI backend para el sistema de Mesa de Ayuda B2B multi-tenant.
|
|
|
|
## Estructura
|
|
|
|
```
|
|
backend/
|
|
├── app/
|
|
│ ├── main.py # FastAPI app principal
|
|
│ ├── core/ # Configuración y utilidades core
|
|
│ │ ├── config.py # Configuración con Pydantic Settings
|
|
│ │ ├── database.py # SQLAlchemy async setup
|
|
│ │ ├── security.py # JWT, hashing, 2FA
|
|
│ │ └── logging.py # Structured logging
|
|
│ ├── models/ # Modelos SQLAlchemy
|
|
│ │ ├── tenant.py # Modelo de tenant (multi-tenancy)
|
|
│ │ ├── user.py # Modelo de usuario
|
|
│ │ └── ... # Otros modelos
|
|
│ ├── api/ # API routes
|
|
│ │ └── v1/ # API version 1
|
|
│ │ ├── router.py # Router principal
|
|
│ │ └── endpoints/ # Endpoints por dominio
|
|
│ ├── middleware/ # Custom middleware
|
|
│ ├── services/ # Business logic
|
|
│ ├── repositories/ # Data access layer
|
|
│ ├── schemas/ # Pydantic schemas
|
|
│ └── utils/ # Utilidades compartidas
|
|
├── tests/ # Tests unitarios e integración
|
|
├── migrations/ # Migraciones Alembic
|
|
├── requirements.txt # Dependencias Python
|
|
└── pyproject.toml # Configuración del proyecto
|
|
```
|
|
|
|
## Características Implementadas
|
|
|
|
### Core
|
|
- [x] FastAPI app con configuración async
|
|
- [x] Pydantic Settings para configuración
|
|
- [x] SQLAlchemy 2.0 async
|
|
- [x] Structured logging con structlog
|
|
- [x] JWT authentication con refresh tokens
|
|
- [x] 2FA con TOTP
|
|
- [x] Multi-tenancy middleware
|
|
|
|
### API
|
|
- [x] Health checks (/health, /health/detailed)
|
|
- [x] Authentication endpoints básicos
|
|
- [x] Middleware de correlation ID y tenant
|
|
- [x] Error handling centralizado
|
|
- [x] CORS configurado
|
|
|
|
### Seguridad
|
|
- [x] Argon2 password hashing
|
|
- [x] JWT con algoritmos seguros
|
|
- [x] TOTP 2FA implementation
|
|
- [x] Validation con Pydantic v2
|
|
|
|
### Rate limiting (login)
|
|
|
|
El endpoint `/{API_VERSION}/auth/login` incluye rate limiting (best-effort) usando Redis:
|
|
|
|
- Por IP: limita intentos totales por ventana
|
|
- Por identidad: limita por `(tenant_id, email)` por ventana
|
|
|
|
Responde `429 Too Many Requests` con header `Retry-After`.
|
|
|
|
Variables de entorno (ver `app/core/config.py`):
|
|
|
|
- `RATE_LIMIT_ENABLED` (default: `true`)
|
|
- `LOGIN_RATE_LIMIT_WINDOW_SECONDS` (default: `300`)
|
|
- `LOGIN_RATE_LIMIT_IP_MAX_ATTEMPTS` (default: `30`)
|
|
- `LOGIN_RATE_LIMIT_ID_MAX_ATTEMPTS` (default: `10`)
|
|
|
|
## Quick Start
|
|
|
|
```bash
|
|
# Instalar dependencias
|
|
pip install -r requirements.txt
|
|
|
|
# Variables de entorno (copiar desde raíz del proyecto)
|
|
cp ../.env.example .env
|
|
|
|
# Ejecutar en desarrollo
|
|
uvicorn app.main:app --reload --port 8000
|
|
|
|
# O usar Docker
|
|
docker-compose up backend
|
|
```
|
|
|
|
## Testing
|
|
|
|
```bash
|
|
# Ejecutar tests
|
|
pytest
|
|
|
|
# Con coverage
|
|
pytest --cov=app tests/
|
|
|
|
# Solo tests unitarios
|
|
pytest -m "unit"
|
|
|
|
# Solo tests de integración
|
|
pytest -m "integration"
|
|
```
|
|
|
|
## Code Quality
|
|
|
|
```bash
|
|
# Linting
|
|
ruff check .
|
|
|
|
# Formateo
|
|
black .
|
|
|
|
# Type checking
|
|
mypy .
|
|
|
|
# Fix automático
|
|
ruff check . --fix
|
|
black .
|
|
```
|
|
|
|
## Desarrollo
|
|
|
|
### Agregar nuevos endpoints
|
|
|
|
1. Crear schema en `app/schemas/`
|
|
2. Crear endpoint en `app/api/v1/endpoints/`
|
|
3. Registrar router en `app/api/v1/router.py`
|
|
4. Agregar tests en `tests/`
|
|
|
|
### Modelos de base de datos
|
|
|
|
1. Crear modelo en `app/models/`
|
|
2. Importar en `app/models/__init__.py`
|
|
3. Crear migración: `alembic revision --autogenerate -m "descripción"`
|
|
4. Aplicar migración: `alembic upgrade head`
|
|
|
|
### Variables de entorno
|
|
|
|
Todas las configuraciones están en `app/core/config.py` usando Pydantic Settings.
|
|
|
|
Ver `.env.example` para todas las variables disponibles.
|
|
|
|
## Arquitectura
|
|
|
|
### Clean Architecture
|
|
|
|
- **Presentation**: FastAPI endpoints y schemas
|
|
- **Application**: Services y casos de uso
|
|
- **Domain**: Entidades y reglas de negocio
|
|
- **Infrastructure**: Repositorios, DB, external APIs
|
|
|
|
### Patrones implementados
|
|
|
|
- Repository pattern para acceso a datos
|
|
- Dependency injection con FastAPI Depends
|
|
- Unit of Work para transacciones
|
|
- Command/Query separation
|
|
|
|
## Monitoring
|
|
|
|
- Structured logging con correlation IDs
|
|
- Health checks para load balancer
|
|
- Métricas con Prometheus (TODO)
|
|
- Error tracking (TODO)
|
|
|
|
## Security Checklist
|
|
|
|
- [x] Password hashing con Argon2
|
|
- [x] JWT con secret keys seguras
|
|
- [x] CORS restrictivo
|
|
- [x] Input validation con Pydantic
|
|
- [x] SQL injection protection (SQLAlchemy)
|
|
- [x] Rate limiting (login)
|
|
- [x] File upload validation (extensión + firma básica + tamaño + streaming)
|
|
- [x] XSS protection (headers en nginx)
|
|
|
|
## Próximos pasos
|
|
|
|
1. Implementar repositorios y services
|
|
2. Completar autenticación con base de datos
|
|
3. Agregar endpoints de users y tickets
|
|
4. Implementar rate limiting
|
|
5. Agregar métricas y monitoring
|
|
6. Tests de integración completos |