- Updated Dockerfile to include hardcoded environment variables for Next.js build. - Enhanced Google Calendar API integration by extracting user email from id_token and adding scopes for OpenID and email access. - Modified credential management to delete existing credentials before creating new ones in n8n. - Updated dashboard to display connected Google Calendar email and credential details. Story: 4.2 - Melhorar integração com Google Calendar e atualizar Dockerfile 🤖 Generated with [Claude Code](https://claude.com/claude-code)
194 lines
5.5 KiB
TypeScript
194 lines
5.5 KiB
TypeScript
import { createServerClient } from "@supabase/ssr";
|
|
import { cookies } from "next/headers";
|
|
import { type NextRequest, NextResponse } from "next/server";
|
|
import { upsertGoogleCredential } from "@/lib/n8n-api";
|
|
|
|
/**
|
|
* GET /api/google-calendar/manage-credential
|
|
*
|
|
* Retorna o ID da credencial "refugio" configurada
|
|
*
|
|
* @returns {credentialId: string}
|
|
*/
|
|
export async function GET(_request: NextRequest) {
|
|
try {
|
|
const cookieStore = await cookies();
|
|
const supabase = createServerClient(
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
|
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
|
{
|
|
cookies: {
|
|
getAll() {
|
|
return cookieStore.getAll();
|
|
},
|
|
setAll(cookiesToSet) {
|
|
for (const { name, value, options } of cookiesToSet) {
|
|
cookieStore.set(name, value, options);
|
|
}
|
|
},
|
|
},
|
|
},
|
|
);
|
|
const {
|
|
data: { user },
|
|
} = await supabase.auth.getUser();
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const credentialId = process.env.N8N_GOOGLE_CREDENTIAL_ID;
|
|
|
|
console.log("[manage-credential] GET - Credential ID:", credentialId);
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
credentialId: credentialId || null,
|
|
});
|
|
} catch (error) {
|
|
console.error("[manage-credential] GET error:", error);
|
|
return NextResponse.json(
|
|
{ success: false, error: "Failed to get credential ID" },
|
|
{ status: 500 },
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST /api/google-calendar/manage-credential
|
|
*
|
|
* Story 3.4: Cria ou atualiza credencial "refugio" no n8n com tokens do Google
|
|
*
|
|
* @body {accessToken, refreshToken, expiresIn}
|
|
* @returns {success: boolean, credentialId: string}
|
|
*/
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const cookieStore = await cookies();
|
|
const supabase = createServerClient(
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
|
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
|
{
|
|
cookies: {
|
|
getAll() {
|
|
return cookieStore.getAll();
|
|
},
|
|
setAll(cookiesToSet) {
|
|
for (const { name, value, options } of cookiesToSet) {
|
|
cookieStore.set(name, value, options);
|
|
}
|
|
},
|
|
},
|
|
},
|
|
);
|
|
const {
|
|
data: { user },
|
|
} = await supabase.auth.getUser();
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const body = await request.json();
|
|
const { accessToken, refreshToken, expiresIn, googleEmail } = body;
|
|
|
|
if (!accessToken || !refreshToken) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Missing required tokens" },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
console.log("[manage-credential] POST - User:", user.id);
|
|
console.log("[manage-credential] Google email received:", googleEmail);
|
|
|
|
const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;
|
|
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
|
|
|
|
if (!clientId || !clientSecret) {
|
|
throw new Error("Google OAuth credentials not configured");
|
|
}
|
|
|
|
// Buscar credential_id anterior do Supabase (se existir)
|
|
const { data: existingIntegration } = await supabase
|
|
.schema("portal")
|
|
.from("integrations")
|
|
.select("n8n_credential_id")
|
|
.eq("user_id", user.id)
|
|
.eq("provider", "google_calendar")
|
|
.maybeSingle();
|
|
|
|
const oldCredentialId = existingIntegration?.n8n_credential_id;
|
|
|
|
console.log(
|
|
"[manage-credential] Old credential ID from Supabase:",
|
|
oldCredentialId || "none",
|
|
);
|
|
|
|
// Upsert credencial "refugio" no n8n
|
|
// Scopes necessários para Google Calendar (incluindo calendar.readonly)
|
|
const result = await upsertGoogleCredential(
|
|
"refugio",
|
|
clientId,
|
|
clientSecret,
|
|
"https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.events",
|
|
accessToken,
|
|
refreshToken,
|
|
expiresIn || 3599,
|
|
oldCredentialId, // Passar credential_id anterior para deletar
|
|
);
|
|
|
|
const credentialId = result.id;
|
|
|
|
console.log(
|
|
"[manage-credential] Credential upserted in n8n:",
|
|
credentialId,
|
|
);
|
|
|
|
// Salvar credentialId, nome e email do Google no Supabase (schema portal)
|
|
// Nome sempre será "refugio" para não quebrar workflows do n8n
|
|
const { error: upsertError } = await supabase
|
|
.schema("portal")
|
|
.from("integrations")
|
|
.upsert(
|
|
{
|
|
user_id: user.id,
|
|
provider: "google_calendar",
|
|
status: "connected",
|
|
n8n_credential_id: credentialId,
|
|
n8n_credential_name: "refugio", // Sempre "refugio"
|
|
connected_email: googleEmail, // Email da conta Google conectada
|
|
connected_at: new Date().toISOString(),
|
|
updated_at: new Date().toISOString(),
|
|
},
|
|
{
|
|
onConflict: "user_id,provider",
|
|
},
|
|
);
|
|
|
|
if (upsertError) {
|
|
console.error("[manage-credential] Supabase upsert error:", upsertError);
|
|
throw upsertError;
|
|
}
|
|
|
|
console.log("[manage-credential] Integration status saved to Supabase");
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
credentialId,
|
|
});
|
|
} catch (error) {
|
|
console.error("[manage-credential] POST error:", error);
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error:
|
|
error instanceof Error
|
|
? error.message
|
|
: "Failed to manage credential",
|
|
},
|
|
{ status: 500 },
|
|
);
|
|
}
|
|
}
|