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
- 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>
6.3 KiB
6.3 KiB
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
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
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
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
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
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
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
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
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
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 - Seccion 5.1
- ARQUITECTURA-TECNICA.md
Ultima Actualizacion: 2026-01-10