template-saas/docs/01-modulos/SAAS-001-auth.md
rckrdmrd 50a821a415
Some checks failed
CI / Backend CI (push) Has been cancelled
CI / Frontend CI (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / CI Summary (push) Has been cancelled
[SIMCO-V38] feat: Actualizar a SIMCO v3.8.0
- HERENCIA-SIMCO.md actualizado con directivas v3.7 y v3.8
- Actualizaciones de configuracion

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 08:53:08 -06:00

205 lines
4.6 KiB
Markdown

---
id: "SAAS-001"
title: "Autenticacion"
type: "Module"
status: "Published"
priority: "P0"
module: "auth"
version: "1.0.0"
created_date: "2026-01-07"
updated_date: "2026-01-10"
---
# SAAS-001: Autenticacion
## Metadata
- **Codigo:** SAAS-001
- **Modulo:** Auth
- **Prioridad:** P0
- **Estado:** Completado
- **Fase:** 1 - Foundation
## Descripcion
Sistema de autenticacion completo para SaaS multi-tenant: JWT con refresh tokens, OAuth 2.0 con multiples proveedores, MFA opcional, y gestion de sesiones.
## Objetivos
1. Login con email/password
2. OAuth 2.0 (Google, Microsoft, GitHub)
3. JWT con refresh tokens
4. MFA (TOTP)
5. Gestion de sesiones
## Alcance
### Incluido
- Registro con email
- Login con email/password
- OAuth 2.0 (Google, Microsoft, GitHub)
- JWT access tokens (15min)
- Refresh tokens (7 dias)
- MFA via TOTP (Google Authenticator)
- Session management
- Password reset flow
- Email verification
### Excluido
- Passwordless (magic links) - fase posterior
- Biometric auth - fase posterior
- SSO/SAML - enterprise feature
## Modelo de Datos
### Tablas (schema: auth)
**sessions**
- id, user_id, token, device_info
- ip_address, user_agent
- expires_at, revoked_at, created_at
**tokens**
- id, user_id, type (verify_email/reset_password/mfa_setup)
- token, expires_at, used_at
**oauth_connections**
- id, user_id, provider (google/microsoft/github)
- provider_id, access_token, refresh_token
- expires_at, created_at
## Endpoints API (Implementados)
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| POST | /auth/register | Registro nuevo usuario |
| POST | /auth/login | Login email/password |
| POST | /auth/logout | Cerrar sesion actual |
| POST | /auth/logout-all | Cerrar todas las sesiones |
| POST | /auth/refresh | Renovar tokens |
| GET | /auth/me | Usuario actual |
| POST | /auth/password/forgot | Solicitar reset |
| POST | /auth/password/reset | Resetear password |
| POST | /auth/verify-email | Verificar email |
## Roadmap (Planificado - No Implementado)
### OAuth 2.0
Autenticacion con proveedores externos:
| Proveedor | Estado |
|-----------|--------|
| Google | Planificado |
| Microsoft | Planificado |
| GitHub | Planificado |
| Apple | Planificado |
**Endpoints planificados:**
- GET `/auth/oauth/:provider` - Iniciar flujo OAuth
- GET `/auth/oauth/:provider/callback` - Callback OAuth
**Nota:** La tabla `auth.oauth_connections` existe en DDL pero los endpoints no estan implementados.
### MFA - Multi-Factor Authentication
Autenticacion de dos factores via TOTP:
**Endpoints planificados:**
- POST `/auth/mfa/setup` - Configurar MFA
- POST `/auth/mfa/verify` - Verificar codigo TOTP
- DELETE `/auth/mfa` - Desactivar MFA
**Campos planificados en User:** mfa_secret, mfa_enabled
### Session Management
Gestion de sesiones activas del usuario:
**Endpoints planificados:**
- GET `/auth/sessions` - Listar sesiones activas
- DELETE `/auth/sessions/:id` - Revocar sesion especifica
## Flujos
### Registro
```
1. Usuario ingresa email, password, nombre
2. Backend valida datos
3. Crea user + tenant (si es owner)
4. Envia email de verificacion
5. Usuario verifica email
6. Puede hacer login
```
### Login con MFA
```
1. Usuario ingresa email/password
2. Backend valida credenciales
3. Si MFA activo: responde {mfa_required: true}
4. Usuario ingresa codigo TOTP
5. Backend valida TOTP
6. Genera JWT + refresh token
7. Usuario autenticado
```
### OAuth Flow
```
1. Usuario click "Login con Google"
2. Redirect a Google
3. Usuario autoriza
4. Google redirige a callback
5. Backend intercambia code por tokens
6. Busca o crea usuario
7. Genera JWT
8. Redirige a app
```
## Seguridad
- Passwords hasheados con bcrypt (cost 12)
- Rate limiting en login (5 intentos/15min)
- Refresh token rotation
- Sesiones revocables
- IP tracking por sesion
- TOTP con drift tolerance
## Entregables
| Entregable | Estado | Archivo |
|------------|--------|---------|
| auth.module.ts | Completado | `modules/auth/` |
| jwt.strategy.ts | Completado | `strategies/` |
| oauth strategies | Completado | `strategies/` |
| DDL auth schema | Completado | `ddl/schemas/auth/` |
## Dependencias
### Depende de
- Ninguno (modulo base)
### Bloquea a
- SAAS-002 (Tenants)
- SAAS-003 (Users)
- Todos los modulos protegidos
## Criterios de Aceptacion
### Implementados
- [x] Registro funciona
- [x] Login funciona
- [x] JWT se genera y valida
- [x] Refresh token funciona
- [x] Password reset funciona
- [x] Email verification funciona
### Pendientes (Roadmap)
- [ ] OAuth Google
- [ ] OAuth Microsoft
- [ ] OAuth GitHub
- [ ] MFA TOTP
- [ ] Session management UI
---
**Ultima actualizacion:** 2026-01-10