Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / admin / pinterest / start / route.ts

1import { NextResponse, type NextRequest } from 'next/server';
2import { randomBytes } from 'node:crypto';
3import { getCustomerUser } from '@/app/lib/lumen-auth';
4import { isAdmin } from '@/app/lib/admin';
5import { authorizeUrl } from '@/app/lib/pinterest';
6
7export const runtime = 'nodejs';
8export const dynamic = 'force-dynamic';
9
10// Kick off the Pinterest OAuth handshake. Admin clicks "Connect Pinterest"
11// on /admin/pinterest; we generate a CSRF `state`, stash it in an HttpOnly
12// cookie, and redirect to Pinterest's authorize URL. The callback route
13// validates the cookie state before trusting the returned `code`.
14export async function GET(req: NextRequest) {
15 const user = await getCustomerUser();
16 if (!user || !isAdmin(user.email)) {
17 return NextResponse.json({ error: 'forbidden' }, { status: 403 });
18 }
19
20 const state = randomBytes(24).toString('hex');
21 let url: string;
22 try {
23 url = authorizeUrl(state);
24 } catch (e) {
25 const msg = e instanceof Error ? e.message : 'pinterest env not configured';
26 return NextResponse.json({ error: msg }, { status: 500 });
27 }
28
29 const res = NextResponse.redirect(url);
30 res.cookies.set('pin_oauth_state', state, {
31 httpOnly: true,
32 secure: req.nextUrl.protocol === 'https:',
33 sameSite: 'lax',
34 path: '/',
35 maxAge: 600, // 10 minutes — plenty for the round-trip
36 });
37 return res;
38}