import { authentikFetch, createAuthentikApplication, createAuthentikProvider, linkProviderToApplication } from '../../utils/authentik'; import { requireAuth } from '../../utils/auth'; // /api/applications - Handle GET and POST export default defineEventHandler(async (event) => { const method = getMethod(event); // Require authentication for all application endpoints await requireAuth(event); switch (method) { case 'GET': try { const applications = await authentikFetch('/core/applications/'); return applications; } catch (error) { throw createError({ statusCode: error.statusCode || 500, message: error.message }); } case 'POST': try { const body = await readBody(event); // Create application in Authentik const application = await createAuthentikApplication({ name: body.name, slug: body.slug || body.name.toLowerCase().replace(/\s+/g, '-'), meta_description: body.description, meta_publisher: 'CorradAF RBAC' }); // Create OAuth2 provider if web application if (body.type === 'web-app') { const provider = await createAuthentikProvider({ name: `${body.name} OAuth2`, client_type: 'confidential', redirect_uris: body.redirectUris, authorization_flow: body.authorizationFlow || 'default-authentication-flow' }); // Link provider to application await linkProviderToApplication(application.pk, provider.pk); } return application; } catch (error) { throw createError({ statusCode: error.statusCode || 500, message: error.message }); } default: throw createError({ statusCode: 405, message: 'Method not allowed' }); } });