Remove unused files and code: - Delete test/debug endpoints (test.get.ts, public.get.ts, user.get.ts, debug-config backup) - Remove unused OAuth wrapper (oauth-authentik.ts) - Clean up debug console.log statements - Simplify code comments Fix TypeScript errors: - Add @types/node dependency - Create index.d.ts with User interface extension - Fix UButton color props (red→error, gray→neutral) - Add type assertions in protected.get.ts Update documentation: - Enhance README.md as template documentation - Update SETUP.md with correct API routes (/api/auth/* instead of /auth/*) - Add NUXT_OAUTH_AUTHENTIK_SERVER_URL_INTERNAL documentation - Update endpoint documentation This commit prepares the repository to be used as a template for future Nuxt 4 + Authentik OAuth projects.
312 lines
8.0 KiB
Markdown
312 lines
8.0 KiB
Markdown
# Guía de Configuración - Seguidor de Lotes
|
|
|
|
## Arquitectura
|
|
|
|
```
|
|
┌─────────────┐ ┌──────────┐ ┌────────────────┐
|
|
│ Traefik │────▶│ Nuxt App │────▶│ Authentik │
|
|
│ (Reverse │ │ (Puerto │ │ (OAuth/OIDC) │
|
|
│ Proxy) │ │ 3000) │ │ │
|
|
└─────────────┘ └──────────┘ └────────────────┘
|
|
│ │
|
|
└───────────────────┘
|
|
Red Docker "principal"
|
|
```
|
|
|
|
## 1. Configurar Authentik
|
|
|
|
### 1.1 Crear Aplicación OAuth en Authentik
|
|
|
|
1. Accede a tu panel de Authentik: `https://auth.tudominio.com`
|
|
2. Ve a **Applications** → **Applications** → **Create**
|
|
3. Configura:
|
|
- **Name**: Seguidor de Lotes
|
|
- **Slug**: seguidor-lotes
|
|
- **Provider**: (Crear nuevo provider OAuth2/OIDC)
|
|
|
|
### 1.2 Crear Provider OAuth2/OIDC
|
|
|
|
1. **Applications** → **Providers** → **Create**
|
|
2. Selecciona **OAuth2/OpenID Provider**
|
|
3. Configura:
|
|
- **Name**: Seguidor de Lotes OAuth
|
|
- **Authorization flow**: default-authentication-flow
|
|
- **Client type**: Confidential
|
|
- **Client ID**: (se genera automáticamente, guárdalo)
|
|
- **Client Secret**: (se genera automáticamente, guárdalo)
|
|
- **Redirect URIs**: `https://app.tudominio.com/api/auth/authentik`
|
|
- **Scopes**: openid, profile, email
|
|
- **Subject mode**: Based on the User's UUID
|
|
- **Include claims in id_token**: ✅ Activado
|
|
|
|
4. Guarda el provider y asócialo a la aplicación creada anteriormente
|
|
|
|
### 1.3 Configurar Grupos (Opcional)
|
|
|
|
Si quieres usar permisos basados en grupos:
|
|
1. **Directory** → **Groups** → **Create**
|
|
2. Crea grupos como: `admin`, `users`, etc.
|
|
3. En el Provider OAuth, asegúrate de incluir el scope `groups`
|
|
|
|
## 2. Configurar Variables de Entorno
|
|
|
|
### 2.1 Copiar archivo de ejemplo
|
|
|
|
```bash
|
|
cp .env.example .env
|
|
```
|
|
|
|
### 2.2 Editar variables en `.env`
|
|
|
|
```bash
|
|
# Dominio de tu aplicación
|
|
APP_DOMAIN=app.tudominio.com
|
|
|
|
# Datos de Authentik OAuth (desde el paso 1.2)
|
|
NUXT_OAUTH_AUTHENTIK_CLIENT_ID=tu-client-id-aqui
|
|
NUXT_OAUTH_AUTHENTIK_CLIENT_SECRET=tu-client-secret-aqui
|
|
NUXT_OAUTH_AUTHENTIK_SERVER_URL=https://auth.tudominio.com
|
|
NUXT_OAUTH_AUTHENTIK_REDIRECT_URL=https://app.tudominio.com/api/auth/authentik
|
|
NUXT_OAUTH_AUTHENTIK_SERVER_URL_INTERNAL=http://nombre-servicio-authentik:9000
|
|
|
|
# URL pública de la app
|
|
NUXT_PUBLIC_APP_URL=https://app.tudominio.com
|
|
|
|
# Secret para sesiones (generar con: openssl rand -base64 32)
|
|
NUXT_SESSION_PASSWORD=$(openssl rand -base64 32)
|
|
```
|
|
|
|
### 2.3 Generar Session Secret
|
|
|
|
```bash
|
|
openssl rand -base64 32
|
|
```
|
|
|
|
Copia el resultado y pégalo en `NUXT_SESSION_PASSWORD`
|
|
|
|
## 3. Configurar Red Docker
|
|
|
|
Asegúrate de que la red `principal` exista:
|
|
|
|
```bash
|
|
# Verificar si existe
|
|
docker network ls | grep principal
|
|
|
|
# Si no existe, crearla
|
|
docker network create principal
|
|
```
|
|
|
|
## 4. Verificar Traefik
|
|
|
|
Tu configuración de Traefik debe tener:
|
|
|
|
```yaml
|
|
# traefik.yml o docker-compose.yml de Traefik
|
|
providers:
|
|
docker:
|
|
network: principal
|
|
exposedByDefault: false
|
|
```
|
|
|
|
## 5. Crear Iconos PWA
|
|
|
|
Crea los iconos en `nuxt4-app/public/`:
|
|
|
|
```bash
|
|
# Necesitas un icono base de 512x512 llamado icon.png
|
|
# Puedes generarlos con imagemagick:
|
|
|
|
cd nuxt4-app/public
|
|
|
|
# Si tienes un SVG o PNG grande
|
|
convert icon.png -resize 192x192 pwa-192x192.png
|
|
convert icon.png -resize 512x512 pwa-512x512.png
|
|
|
|
# O usa una herramienta online: https://realfavicongenerator.net/
|
|
```
|
|
|
|
## 6. Desplegar
|
|
|
|
### 6.1 Build y Start
|
|
|
|
```bash
|
|
# Build y levantar el contenedor
|
|
docker-compose up -d --build
|
|
```
|
|
|
|
### 6.2 Ver logs
|
|
|
|
```bash
|
|
docker-compose logs -f seguidor-lotes
|
|
```
|
|
|
|
### 6.3 Verificar estado
|
|
|
|
```bash
|
|
docker-compose ps
|
|
```
|
|
|
|
## 7. Verificar Funcionamiento
|
|
|
|
### 7.1 Acceso Web
|
|
|
|
1. Accede a `https://app.tudominio.com`
|
|
2. Deberías ver la página de inicio
|
|
3. Click en "Iniciar Sesión"
|
|
4. Serás redirigido a Authentik
|
|
5. Tras autenticar, vuelves a la app con sesión iniciada
|
|
|
|
### 7.2 Verificar APIs
|
|
|
|
```bash
|
|
# API Protegida (requiere auth - debería retornar 401 sin sesión)
|
|
curl https://app.tudominio.com/api/protected
|
|
```
|
|
|
|
### 7.3 Verificar PWA
|
|
|
|
1. Abre Chrome DevTools (F12)
|
|
2. Ve a la pestaña **Application** → **Service Workers**
|
|
3. Deberías ver el service worker registrado
|
|
4. Prueba el modo offline:
|
|
- Activa "Offline" en la pestaña Network
|
|
- Navega por la aplicación
|
|
- Las páginas cacheadas funcionarán sin conexión
|
|
|
|
## 8. Rutas y Endpoints
|
|
|
|
### Páginas
|
|
|
|
- `/` - Página de inicio (pública)
|
|
- `/login` - Página de login
|
|
- `/dashboard` - Dashboard (requiere autenticación)
|
|
- `/profile` - Perfil (requiere autenticación)
|
|
|
|
### API Endpoints
|
|
|
|
- `GET /api/protected` - Endpoint protegido (requiere autenticación)
|
|
|
|
### Auth Endpoints
|
|
|
|
- `GET /api/auth/authentik` - Inicia OAuth flow con Authentik y maneja callback
|
|
- `GET /api/auth/logout` - Cierra sesión
|
|
|
|
## 9. Desarrollo Local
|
|
|
|
Si quieres desarrollar localmente sin Docker:
|
|
|
|
```bash
|
|
cd nuxt4-app
|
|
|
|
# Copiar variables de entorno
|
|
cp .env.example .env
|
|
|
|
# Editar .env con tus valores locales
|
|
# Usar http://localhost:3000 en lugar de https
|
|
|
|
# Instalar dependencias
|
|
npm install
|
|
|
|
# Ejecutar en modo desarrollo
|
|
npm run dev
|
|
```
|
|
|
|
**Nota**: Para desarrollo local, necesitas:
|
|
- Configurar Authentik con redirect URI: `http://localhost:3000/api/auth/authentik`
|
|
- O usar túnel como ngrok para https
|
|
- Usar la URL pública de Authentik para `NUXT_OAUTH_AUTHENTIK_SERVER_URL`
|
|
- No necesitas `NUXT_OAUTH_AUTHENTIK_SERVER_URL_INTERNAL` en desarrollo local
|
|
|
|
## 10. Troubleshooting
|
|
|
|
### Error: "Invalid redirect_uri"
|
|
|
|
- Verifica que la URI en Authentik coincida exactamente con `NUXT_OAUTH_AUTHENTIK_REDIRECT_URL`
|
|
- El protocolo debe ser `https://` en producción
|
|
|
|
### Error: "Invalid client_id or client_secret"
|
|
|
|
- Verifica los valores copiados de Authentik
|
|
- Asegúrate de que el Provider esté activado
|
|
|
|
### PWA no se registra
|
|
|
|
- Verifica que estés usando HTTPS (obligatorio para service workers)
|
|
- Abre DevTools → Application → Service Workers
|
|
- Verifica errores en la consola
|
|
|
|
### Sesión no persiste
|
|
|
|
- Verifica que `NUXT_SESSION_PASSWORD` tenga al menos 32 caracteres
|
|
- Verifica las cookies en DevTools → Application → Cookies
|
|
|
|
### Container no inicia
|
|
|
|
```bash
|
|
# Ver logs detallados
|
|
docker-compose logs seguidor-lotes
|
|
|
|
# Ver todas las variables de entorno
|
|
docker-compose exec seguidor-lotes env | grep NUXT
|
|
```
|
|
|
|
## 11. Seguridad
|
|
|
|
### Recomendaciones
|
|
|
|
1. **HTTPS Obligatorio**: Nunca uses HTTP en producción
|
|
2. **Secrets Seguros**: Usa `openssl rand -base64 32` para generar secrets
|
|
3. **Variables de Entorno**: Nunca commits el archivo `.env`
|
|
4. **Rate Limiting**: Considera añadir rate limiting en Traefik
|
|
5. **CORS**: Configura CORS apropiadamente si usas subdominios
|
|
|
|
### Headers de Seguridad (Traefik)
|
|
|
|
Añade a los labels de Docker Compose:
|
|
|
|
```yaml
|
|
- "traefik.http.middlewares.security-headers.headers.stsSeconds=31536000"
|
|
- "traefik.http.middlewares.security-headers.headers.stsIncludeSubdomains=true"
|
|
- "traefik.http.middlewares.security-headers.headers.stsPreload=true"
|
|
- "traefik.http.middlewares.security-headers.headers.contentTypeNosniff=true"
|
|
- "traefik.http.middlewares.security-headers.headers.browserXssFilter=true"
|
|
- "traefik.http.routers.seguidor-lotes.middlewares=security-headers"
|
|
```
|
|
|
|
## 12. Personalización
|
|
|
|
### Cambiar nombre de la app
|
|
|
|
1. Edita `nuxt4-app/nuxt.config.ts` → sección `pwa.manifest`
|
|
2. Cambia `name` y `short_name`
|
|
|
|
### Añadir más rutas protegidas
|
|
|
|
Crea una nueva página con:
|
|
|
|
```vue
|
|
<script setup>
|
|
definePageMeta({
|
|
middleware: 'auth'
|
|
})
|
|
</script>
|
|
```
|
|
|
|
### Añadir más endpoints protegidos
|
|
|
|
Crea un archivo en `server/api/` con:
|
|
|
|
```typescript
|
|
export default defineEventHandler(async (event) => {
|
|
const session = await requireUserSession(event)
|
|
// Tu lógica aquí
|
|
})
|
|
```
|
|
|
|
## Soporte
|
|
|
|
Para más información:
|
|
- [Nuxt Auth Utils](https://github.com/atinux/nuxt-auth-utils)
|
|
- [Vite PWA](https://vite-pwa-org.netlify.app/)
|
|
- [Authentik Docs](https://docs.goauthentik.io/)
|