File size: 2,706 Bytes
6111b2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | import { NextResponse } from "next/server";
import { validateApiKey, getProviderConnections, updateProviderConnection } from "@/models";
import { cloudCredentialUpdateSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
// Update provider credentials (for cloud token refresh)
export async function PUT(request: Request) {
let rawBody;
try {
rawBody = await request.json();
} catch {
return NextResponse.json(
{ error: { message: "Invalid request", details: [{ field: "body", message: "Invalid JSON body" }] } },
{ status: 400 }
);
}
try {
const authHeader = request.headers.get("Authorization");
if (!authHeader?.startsWith("Bearer ")) {
return NextResponse.json({ error: "Missing API key" }, { status: 401 });
}
const apiKey = authHeader.slice(7);
const validation = validateBody(cloudCredentialUpdateSchema, rawBody);
if (isValidationFailure(validation)) {
return NextResponse.json({ error: validation.error }, { status: 400 });
}
const { provider, credentials } = validation.data;
// Validate API key
const isValid = await validateApiKey(apiKey);
if (!isValid) {
return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
}
// Find active connection for provider
const connections = await getProviderConnections({ provider, isActive: true });
const connection = connections[0];
if (!connection) {
return NextResponse.json(
{ error: `No active connection found for provider: ${provider}` },
{ status: 404 }
);
}
// Update credentials
const updateData: Record<string, unknown> = {};
if (credentials.accessToken) {
updateData.accessToken = credentials.accessToken;
}
if (credentials.refreshToken) {
updateData.refreshToken = credentials.refreshToken;
}
if (credentials.expiresIn) {
updateData.expiresAt = new Date(Date.now() + credentials.expiresIn * 1000).toISOString();
}
const connectionId = typeof connection.id === "string" ? connection.id : null;
if (!connectionId) {
return NextResponse.json({ error: "Invalid provider connection ID" }, { status: 500 });
}
await updateProviderConnection(connectionId, updateData);
return NextResponse.json({
success: true,
message: `Credentials updated for provider: ${provider}`,
});
} catch (error) {
console.log("Update credentials error:", error);
return NextResponse.json({ error: "Failed to update credentials" }, { status: 500 });
}
}
|