import { NextResponse, type NextRequest } from 'next/server'; import { randomBytes } from 'node:crypto'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { isAdmin } from '@/app/lib/admin'; import { authorizeUrl } from '@/app/lib/pinterest'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // Kick off the Pinterest OAuth handshake. Admin clicks "Connect Pinterest" // on /admin/pinterest; we generate a CSRF `state`, stash it in an HttpOnly // cookie, and redirect to Pinterest's authorize URL. The callback route // validates the cookie state before trusting the returned `code`. export async function GET(req: NextRequest) { const user = await getCustomerUser(); if (!user || !isAdmin(user.email)) { return NextResponse.json({ error: 'forbidden' }, { status: 403 }); } const state = randomBytes(24).toString('hex'); let url: string; try { url = authorizeUrl(state); } catch (e) { const msg = e instanceof Error ? e.message : 'pinterest env not configured'; return NextResponse.json({ error: msg }, { status: 500 }); } const res = NextResponse.redirect(url); res.cookies.set('pin_oauth_state', state, { httpOnly: true, secure: req.nextUrl.protocol === 'https:', sameSite: 'lax', path: '/', maxAge: 600, // 10 minutes — plenty for the round-trip }); return res; }