/** * API endpoint para gestionar información del usuario en Authentik * Soporta GET (obtener) y PATCH (actualizar) */ export default defineEventHandler(async (event) => { const config = useRuntimeConfig() const headers = getRequestHeaders(event) const method = event.method // Obtener el username desde los headers de Authentik const username = headers['x-authentik-username'] if (!username) { throw createError({ statusCode: 401, message: 'Usuario no autenticado' }) } // Obtener la URL y token de Authentik desde variables de entorno const authentikUrl = config.authentikApiUrl || config.public.authentikUrl const authentikToken = config.authentikApiToken if (!authentikToken) { throw createError({ statusCode: 500, message: 'Token de Authentik no configurado' }) } try { if (method === 'GET') { // GET: Obtener información del usuario console.log('🔍 Buscando usuario con username:', username) console.log('🌐 URL de Authentik:', authentikUrl) const response = await $fetch(`${authentikUrl}/api/v3/core/users/?username=${username}`, { headers: { 'Authorization': `Bearer ${authentikToken}`, 'Content-Type': 'application/json' } }) const users = response as any console.log('📊 Respuesta de Authentik:', JSON.stringify(users, null, 2)) if (!users.results || users.results.length === 0) { throw createError({ statusCode: 404, message: 'Usuario no encontrado' }) } return users.results[0] } else if (method === 'PATCH') { // PATCH: Actualizar información del usuario const body = await readBody(event) // Primero, obtener el ID del usuario const usersResponse = await $fetch(`${authentikUrl}/api/v3/core/users/?username=${username}`, { headers: { 'Authorization': `Bearer ${authentikToken}`, 'Content-Type': 'application/json' } }) const users = usersResponse as any if (!users.results || users.results.length === 0) { throw createError({ statusCode: 404, message: 'Usuario no encontrado' }) } const userId = users.results[0].pk // Actualizar el usuario const updateResponse = await $fetch(`${authentikUrl}/api/v3/core/users/${userId}/`, { method: 'PATCH', headers: { 'Authorization': `Bearer ${authentikToken}`, 'Content-Type': 'application/json' }, body: { name: body.name, ...(body.email && { email: body.email }) } }) return updateResponse } else { throw createError({ statusCode: 405, message: 'Método no permitido' }) } } catch (error: any) { console.error('Error en API de Authentik:', error) throw createError({ statusCode: error.statusCode || 500, message: error.message || 'Error al procesar la petición' }) } })