import { NextResponse, type NextRequest } from 'next/server'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { isAdmin } from '@/app/lib/admin'; import { exchangeCodeForTokens, saveRefreshToken } from '@/app/lib/pinterest'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // OAuth callback. Pinterest redirects here with ?code=…&state=… after the // admin authorizes the app. We verify state (set by /start), exchange the // code for tokens, and render an HTML page that DISPLAYS the refresh token // for the admin to paste into PINTEREST_REFRESH_TOKEN. We deliberately do // NOT store the token server-side — copy-paste once into env, done for ~1y. function htmlPage(body: string): string { return ` Pinterest connected — Lumen & Gesso
${body}
`; } export async function GET(req: NextRequest) { const user = await getCustomerUser(); if (!user || !isAdmin(user.email)) { return new NextResponse(htmlPage('

Forbidden

Sign in as an admin and retry.

'), { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' }, }); } const code = req.nextUrl.searchParams.get('code'); const state = req.nextUrl.searchParams.get('state'); const cookieState = req.cookies.get('pin_oauth_state')?.value; const errParam = req.nextUrl.searchParams.get('error'); if (errParam) { return new NextResponse(htmlPage(`

Pinterest declined

${errParam}
Back`), { status: 400, headers: { 'content-type': 'text/html; charset=utf-8' }, }); } if (!code || !state || !cookieState || state !== cookieState) { return new NextResponse(htmlPage('

Invalid callback

Missing code or state mismatch. Re-start the flow.
Back'), { status: 400, headers: { 'content-type': 'text/html; charset=utf-8' }, }); } let tokens; try { tokens = await exchangeCodeForTokens(code); } catch (e) { const msg = e instanceof Error ? e.message : 'token exchange failed'; return new NextResponse(htmlPage(`

Token exchange failed

${msg}
Back`), { status: 502, headers: { 'content-type': 'text/html; charset=utf-8' }, }); } if (!tokens.refresh_token) { return new NextResponse(htmlPage(`

Connected, but no refresh token

Pinterest returned an access token but no refresh token. Re-run the connect flow and ensure all four scopes are granted.
Back`), { status: 502, headers: { 'content-type': 'text/html; charset=utf-8' }, }); } // Persist the refresh token to the integrations table so the lib can use // it immediately. No more copy/paste into env required — Disconnect on // /admin/pinterest wipes it from the same place. try { await saveRefreshToken(tokens.refresh_token); } catch (e) { const msg = e instanceof Error ? e.message : 'save failed'; return new NextResponse(htmlPage(`

Token received but not saved

${msg}
Back`), { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' }, }); } const expiresDays = tokens.refresh_token_expires_in ? Math.round(tokens.refresh_token_expires_in / 86400) : '~365'; const body = `

Pinterest connected ✓

Your refresh token has been saved to the studio database — no env edits required. It lasts about ${expiresDays} days; reconnect anytime via the setup page.

Granted scopes: ${tokens.scope || '(unknown)'}

The per-tile "Pin" action on /admin/images is now live.

Back to setup `; // Clear the OAuth state cookie now that it's been consumed. const res = new NextResponse(htmlPage(body), { headers: { 'content-type': 'text/html; charset=utf-8' } }); res.cookies.set('pin_oauth_state', '', { path: '/', maxAge: 0 }); return res; }