import { NextRequest, NextResponse } from 'next/server'; const CASBIN_SERVER_URL = process.env.CASBIN_SERVER_URL || 'http://localhost:8080'; export async function POST(request: NextRequest) { try { const body = await request.json(); const { action, role } = body; if (!action || !role) { return NextResponse.json( { error: 'Missing action or role parameter' }, { status: 400 } ); } let endpoint = ''; let method = 'POST'; switch (action) { case 'add': endpoint = '/api/v1/roles'; method = 'POST'; break; case 'delete': endpoint = `/api/v1/roles/${encodeURIComponent(role)}`; method = 'DELETE'; break; default: return NextResponse.json( { error: 'Invalid action. Use "add" or "delete"' }, { status: 400 } ); } const casbinResponse = await fetch(`${CASBIN_SERVER_URL}${endpoint}`, { method, headers: { 'Content-Type': 'application/json', 'Authorization': request.headers.get('authorization') || '', }, body: action === 'add' ? JSON.stringify({ role }) : undefined, }); if (!casbinResponse.ok) { const errorText = await casbinResponse.text(); throw new Error(`Casbin server responded with status: ${casbinResponse.status}, body: ${errorText}`); } const data = await casbinResponse.json(); return NextResponse.json({ success: true, data, action, role }); } catch (error) { console.error('Casbin role operation error:', error); return NextResponse.json( { error: 'Failed to perform role operation', message: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } } export async function GET(request: NextRequest) { try { const casbinResponse = await fetch(`${CASBIN_SERVER_URL}/api/v1/roles`, { method: 'GET', headers: { 'Authorization': request.headers.get('authorization') || '', }, }); if (!casbinResponse.ok) { throw new Error(`Casbin server responded with status: ${casbinResponse.status}`); } const data = await casbinResponse.json(); return NextResponse.json(data); } catch (error) { console.error('Casbin get roles error:', error); return NextResponse.json( { error: 'Failed to get roles', message: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } }