Fix: override agents/list API in frontend to use protected_label from MongoDB directly

This commit is contained in:
ypratama committed 2026-09-09 16:10:34 +07:00
1 parent 0b824f8cd2
commit b6bd0f42f6
1 file changed
+85
@@ -0,0 +1,85 @@
/**
* GET /api/dashboard/agents/list
*
* Override route: bypass backend container dan baca langsung dari MongoDB.
* Prioritaskan protected_label agar label tidak teroverwrite oleh proxy lama.
*/
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import mongoose from 'mongoose';
const JWT_SECRET = process.env.JWT_SECRET || 'super-secret-backone-key';
const MONGODB_URI = process.env.MONGODB_URI || '';
async function connectMongo() {
if (mongoose.connection.readyState !== 1) {
await mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 5000 });
}
return mongoose.connection.db!;
}
export async function GET(req: NextRequest) {
try {
// Verify JWT from cookie
const cookieStore = await cookies();
const token = cookieStore.get('token')?.value;
if (!token) {
return NextResponse.json({ ok: false, error: 'Unauthorized' }, { status: 401 });
}
let user: any;
try {
user = jwt.verify(token, JWT_SECRET) as any;
} catch {
return NextResponse.json({ ok: false, error: 'Invalid token' }, { status: 401 });
}
const db = await connectMongo();
const companyRoles = ['COMPANY_ADMIN', 'COMPANY_OPERATOR', 'COMPANY_VIEWER'];
const isCompanyRole = companyRoles.includes(user?.role);
const filter: any = {};
if (isCompanyRole) {
const agentUuids: string[] = user?.agent_uuids || [];
if (agentUuids.length === 0) {
return NextResponse.json({ ok: true, data: [] });
}
filter.uuid = { $in: agentUuids };
} else {
// Admin/SUPER_ADMIN: filter by site UUID
const siteUuidHeader = req.headers.get('x-backone-site-uuid');
const effectiveRole = user?._originalRole || user?.role;
const isGlobalUser = effectiveRole === 'SUPER_ADMIN' || effectiveRole === 'EXECUTIVE';
const envSites = (process.env.BACKONE_SITE_UUIDS || process.env.BACKONE_SITE_UUID || '')
.split(',').map((s: string) => s.trim()).filter(Boolean);
if (isGlobalUser && siteUuidHeader && siteUuidHeader !== 'all' && envSites.includes(siteUuidHeader)) {
filter.site_uuid = { $in: [siteUuidHeader, 'global'] };
} else if (envSites.length > 0) {
filter.site_uuid = { $in: [...envSites, 'global'] };
}
}
const agents = await db.collection('agent_registry')
.find(filter)
.project({ uuid: 1, label: 1, protected_label: 1, _id: 0 })
.sort({ uuid: 1 })
.toArray();
// Prioritaskan protected_label untuk mencegah UUID overwrite dari proxy lama
const mappedAgents = agents.map((a: any) => ({
uuid: a.uuid,
label: a.protected_label || a.label || a.uuid,
}));
return NextResponse.json({ ok: true, data: mappedAgents });
} catch (err: any) {
console.error('[agents/list override]', err.message);
return NextResponse.json({ ok: false, error: err.message }, { status: 500 });
}
}