mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 13:38:31 +00:00
- Add isActive field to API key schema with migration - Implement PUT /api/keys/[id] endpoint for toggle - Update validation to reject paused keys (403) - Add UI toggle controls with confirmation - Ensure cloud sync preserves pause state
80 lines
2.3 KiB
JavaScript
80 lines
2.3 KiB
JavaScript
import { NextResponse } from "next/server";
|
|
import { deleteApiKey, getApiKeyById, updateApiKey, isCloudEnabled } from "@/lib/localDb";
|
|
import { getConsistentMachineId } from "@/shared/utils/machineId";
|
|
import { syncToCloud } from "@/app/api/sync/cloud/route";
|
|
|
|
// GET /api/keys/[id] - Get single key
|
|
export async function GET(request, { params }) {
|
|
try {
|
|
const { id } = await params;
|
|
const key = await getApiKeyById(id);
|
|
if (!key) {
|
|
return NextResponse.json({ error: "Key not found" }, { status: 404 });
|
|
}
|
|
return NextResponse.json({ key });
|
|
} catch (error) {
|
|
console.log("Error fetching key:", error);
|
|
return NextResponse.json({ error: "Failed to fetch key" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// PUT /api/keys/[id] - Update key
|
|
export async function PUT(request, { params }) {
|
|
try {
|
|
const { id } = await params;
|
|
const body = await request.json();
|
|
const { isActive } = body;
|
|
|
|
const existing = await getApiKeyById(id);
|
|
if (!existing) {
|
|
return NextResponse.json({ error: "Key not found" }, { status: 404 });
|
|
}
|
|
|
|
const updateData = {};
|
|
if (isActive !== undefined) updateData.isActive = isActive;
|
|
|
|
const updated = await updateApiKey(id, updateData);
|
|
await syncKeysToCloudIfEnabled();
|
|
|
|
return NextResponse.json({ key: updated });
|
|
} catch (error) {
|
|
console.log("Error updating key:", error);
|
|
return NextResponse.json({ error: "Failed to update key" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// DELETE /api/keys/[id] - Delete API key
|
|
export async function DELETE(request, { params }) {
|
|
try {
|
|
const { id } = await params;
|
|
|
|
const deleted = await deleteApiKey(id);
|
|
if (!deleted) {
|
|
return NextResponse.json({ error: "Key not found" }, { status: 404 });
|
|
}
|
|
|
|
// Auto sync to Cloud if enabled
|
|
await syncKeysToCloudIfEnabled();
|
|
|
|
return NextResponse.json({ message: "Key deleted successfully" });
|
|
} catch (error) {
|
|
console.log("Error deleting key:", error);
|
|
return NextResponse.json({ error: "Failed to delete key" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Sync API keys to Cloud if enabled
|
|
*/
|
|
async function syncKeysToCloudIfEnabled() {
|
|
try {
|
|
const cloudEnabled = await isCloudEnabled();
|
|
if (!cloudEnabled) return;
|
|
|
|
const machineId = await getConsistentMachineId();
|
|
await syncToCloud(machineId);
|
|
} catch (error) {
|
|
console.log("Error syncing keys to cloud:", error);
|
|
}
|
|
}
|