miinventario-v2/docs/01-epicas/MII-002-autenticacion.md
rckrdmrd c24f889f70
Some checks failed
Build / Build Backend (push) Has been cancelled
Build / Build Mobile (TypeScript Check) (push) Has been cancelled
Lint / Lint Backend (push) Has been cancelled
Lint / Lint Mobile (push) Has been cancelled
Test / Backend E2E Tests (push) Has been cancelled
Test / Mobile Unit Tests (push) Has been cancelled
Build / Build Docker Image (push) Has been cancelled
[MIINVENTARIO] feat: Add exports, reports, integrations modules and CI/CD pipeline
- Add exports module with PDF/CSV/Excel generation
- Add reports module for inventory analytics
- Add POS integrations module
- Add database migrations for exports, movements and integrations
- Add GitHub Actions CI/CD workflow with Docker support
- Add mobile export and reports screens with tests
- Update epic documentation with traceability
- Add deployment and security guides

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 06:06:34 -06:00

251 lines
6.3 KiB
Markdown

# MII-002: Autenticacion
---
id: MII-002
type: Epic
status: Completado
priority: P0
phase: 1
story_points: 13
created_date: 2026-01-10
updated_date: 2026-01-13
simco_version: "4.0.0"
---
## Metadata
| Campo | Valor |
|-------|-------|
| **ID** | MII-002 |
| **Nombre** | Autenticacion |
| **Fase** | 1 - MVP Core |
| **Prioridad** | P0 |
| **Story Points** | 13 |
| **Estado** | Completado |
---
## 1. Descripcion
Implementar el sistema de autenticacion completo incluyendo registro con OTP, inicio de sesion, manejo de tokens JWT, y gestion de perfil de usuario.
### Objetivo
Permitir a los usuarios registrarse, autenticarse de forma segura, y mantener sesiones persistentes.
---
## 2. Requerimientos Relacionados
| RF | Descripcion | Prioridad |
|----|-------------|-----------|
| FR-001 | Registro con telefono/email y OTP | P0 |
| FR-002 | Inicio de sesion con refresh tokens | P0 |
| FR-003 | Perfil (nombre, negocio, ubicacion, giro) | P1 |
| FR-004 | Consentimientos (terminos, privacidad, opt-in) | P0 |
---
## 3. Criterios de Aceptacion
### AC-001: Registro con OTP
```gherkin
DADO que soy un usuario nuevo
CUANDO ingreso mi telefono o email
ENTONCES recibo un codigo OTP
Y al verificarlo mi cuenta se crea exitosamente
Y puedo acceder a la aplicacion
```
### AC-002: Inicio de Sesion
```gherkin
DADO que tengo una cuenta registrada
CUANDO ingreso mis credenciales
ENTONCES recibo un access token (15min) y refresh token (7d)
Y puedo acceder a endpoints protegidos
```
### AC-003: Renovacion de Token
```gherkin
DADO que mi access token expiro
CUANDO envio mi refresh token valido
ENTONCES recibo un nuevo par de tokens
Y mi sesion continua sin interrupcion
```
### AC-004: Perfil de Usuario
```gherkin
DADO que estoy autenticado
CUANDO actualizo mi perfil
ENTONCES los cambios se guardan (nombre, ubicacion, giro)
Y puedo ver mi informacion actualizada
```
### AC-005: Consentimientos
```gherkin
DADO que me estoy registrando
CUANDO acepto los terminos y condiciones
ENTONCES mi consentimiento queda registrado con timestamp
Y puedo gestionar opt-in/opt-out para mejora del modelo IA
```
---
## 4. Tareas Tecnicas
| ID | Tarea | Estimacion | Estado |
|----|-------|------------|--------|
| T-001 | Crear modulo auth en NestJS | 1 SP | Completado |
| T-002 | Implementar entidad User | 1 SP | Completado |
| T-003 | Configurar Passport con JWT strategy | 2 SP | Completado |
| T-004 | Implementar servicio de OTP | 2 SP | Completado |
| T-005 | Crear endpoints registro/login | 2 SP | Completado |
| T-006 | Implementar refresh token rotation | 1 SP | Completado |
| T-007 | Crear pantallas auth en mobile | 2 SP | Completado |
| T-008 | Implementar store de auth (Zustand) | 1 SP | Completado |
| T-009 | Agregar consentimientos a registro | 1 SP | Completado |
---
## 5. Modelo de Datos
### Tabla: users
```sql
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
phone VARCHAR(20) UNIQUE,
email VARCHAR(255) UNIQUE,
password_hash VARCHAR(255),
name VARCHAR(100),
business_name VARCHAR(100),
location VARCHAR(255),
giro VARCHAR(50),
role VARCHAR(20) DEFAULT 'USER',
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
```
### Tabla: sessions
```sql
CREATE TABLE sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id),
refresh_token_hash VARCHAR(255),
device_info JSONB,
expires_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
```
### Tabla: otp_codes
```sql
CREATE TABLE otp_codes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_identifier VARCHAR(255),
code VARCHAR(6),
type VARCHAR(20), -- 'registration', 'login', 'reset'
attempts INT DEFAULT 0,
expires_at TIMESTAMP,
verified_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
```
### Tabla: consents
```sql
CREATE TABLE consents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id),
type VARCHAR(50), -- 'terms', 'privacy', 'ml_training'
accepted BOOLEAN,
version VARCHAR(20),
accepted_at TIMESTAMP,
ip_address VARCHAR(45)
);
```
---
## 6. Endpoints API
| Metodo | Endpoint | Descripcion | Auth |
|--------|----------|-------------|------|
| POST | /auth/register | Iniciar registro con OTP | No |
| POST | /auth/verify-otp | Verificar OTP y crear cuenta | No |
| POST | /auth/login | Iniciar sesion | No |
| POST | /auth/refresh | Renovar tokens | Refresh |
| POST | /auth/logout | Cerrar sesion | JWT |
| GET | /users/me | Obtener perfil | JWT |
| PATCH | /users/me | Actualizar perfil | JWT |
| GET | /users/me/consents | Obtener consentimientos | JWT |
| PATCH | /users/me/consents | Actualizar consentimientos | JWT |
---
## 7. Pantallas Mobile
| Pantalla | Componentes |
|----------|-------------|
| **WelcomeScreen** | Logo, botones Login/Register |
| **RegisterScreen** | Input telefono/email, enviar OTP |
| **OTPScreen** | Input codigo, reenviar, verificar |
| **ProfileSetupScreen** | Nombre, negocio, giro |
| **ConsentScreen** | Checkboxes terminos, opt-in |
| **LoginScreen** | Input credenciales, recuperar |
---
## 8. Dependencias
### Entrada (Requiere)
- MII-001: Infraestructura Base
### Salida (Bloquea)
- MII-003: Gestion de Tiendas
- MII-004: Captura de Video
- Todas las funcionalidades que requieren usuario
---
## 9. Seguridad
| Aspecto | Implementacion |
|---------|----------------|
| Passwords | bcrypt con salt rounds 12 |
| Tokens | JWT RS256, rotacion de refresh |
| OTP | 6 digitos, expira en 5min, max 3 intentos |
| Rate Limit | 5 intentos/min por IP |
| Lockout | 15min despues de 5 fallos |
---
## 10. Riesgos
| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| SMS no llega | Media | Alto | Fallback a email, retry logic |
| Token leak | Baja | Alto | Short TTL, refresh rotation |
| Brute force | Media | Medio | Rate limit, lockout |
---
## 11. Notas de Implementacion
- Usar Twilio o similar para SMS (o mock en desarrollo)
- Implementar magic link como alternativa a OTP
- Considerar login con redes sociales post-MVP
- Guardar device fingerprint para seguridad adicional
---
## 12. Referencias
- [REQUERIMIENTOS-FUNCIONALES.md](../00-vision-general/REQUERIMIENTOS-FUNCIONALES.md) - Seccion 5.1
- [ARQUITECTURA-TECNICA.md](../00-vision-general/ARQUITECTURA-TECNICA.md)
---
**Ultima Actualizacion:** 2026-01-10