Branchwell

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

Raw 5.1 KB on f4d070c0cd6547ed6432bda0f7f1dc2cb2181b18
1import { NextResponse, type NextRequest } from 'next/server';
2import { getCustomerUser } from '@/app/lib/lumen-auth';
3import { isAdmin } from '@/app/lib/admin';
4import { exchangeCodeForTokens, saveRefreshToken } from '@/app/lib/pinterest';
5
6export const runtime = 'nodejs';
7export const dynamic = 'force-dynamic';
8
9// OAuth callback. Pinterest redirects here with ?code=…&state=… after the
10// admin authorizes the app. We verify state (set by /start), exchange the
11// code for tokens, and render an HTML page that DISPLAYS the refresh token
12// for the admin to paste into PINTEREST_REFRESH_TOKEN. We deliberately do
13// NOT store the token server-side — copy-paste once into env, done for ~1y.
14function htmlPage(body: string): string {
15 return `<!doctype html><html lang="en"><head><meta charset="utf-8">
16<title>Pinterest connected — Lumen & Gesso</title>
17<style>
18 body{margin:0;padding:48px 24px;background:#f7f2ea;color:#1f1a16;font:15px/1.55 -apple-system,system-ui,sans-serif}
19 main{max-width:720px;margin:0 auto;background:#fff;border:1px solid #ead8c4;border-radius:12px;padding:32px 36px}
20 h1{font-family:'Newsreader',serif;font-size:30px;margin:0 0 8px;letter-spacing:-0.01em}
21 h2{font-size:13px;font-weight:700;letter-spacing:0.16em;text-transform:uppercase;color:#9a574e;margin:28px 0 8px}
22 pre{background:#1d1a17;color:#f3eadd;padding:14px 16px;border-radius:8px;overflow-x:auto;font-size:13px;line-height:1.4;margin:6px 0}
23 code{background:#f3ebde;padding:1px 6px;border-radius:4px;font-size:13px}
24 a.btn{display:inline-block;margin-top:18px;padding:9px 16px;border-radius:8px;background:#1f1a16;color:#fff;text-decoration:none;font-size:14px}
25 .err{background:#fde0dc;border:1px solid #f4a8a0;color:#8a2c22;padding:12px 14px;border-radius:8px}
26</style></head><body><main>${body}</main></body></html>`;
27}
28
29export async function GET(req: NextRequest) {
30 const user = await getCustomerUser();
31 if (!user || !isAdmin(user.email)) {
32 return new NextResponse(htmlPage('<h1>Forbidden</h1><p>Sign in as an admin and retry.</p>'), {
33 status: 403, headers: { 'content-type': 'text/html; charset=utf-8' },
34 });
35 }
36
37 const code = req.nextUrl.searchParams.get('code');
38 const state = req.nextUrl.searchParams.get('state');
39 const cookieState = req.cookies.get('pin_oauth_state')?.value;
40 const errParam = req.nextUrl.searchParams.get('error');
41
42 if (errParam) {
43 return new NextResponse(htmlPage(`<h1>Pinterest declined</h1><div class="err">${errParam}</div><a class="btn" href="/admin/pinterest">Back</a>`), {
44 status: 400, headers: { 'content-type': 'text/html; charset=utf-8' },
45 });
46 }
47 if (!code || !state || !cookieState || state !== cookieState) {
48 return new NextResponse(htmlPage('<h1>Invalid callback</h1><div class="err">Missing code or state mismatch. Re-start the flow.</div><a class="btn" href="/admin/pinterest">Back</a>'), {
49 status: 400, headers: { 'content-type': 'text/html; charset=utf-8' },
50 });
51 }
52
53 let tokens;
54 try {
55 tokens = await exchangeCodeForTokens(code);
56 } catch (e) {
57 const msg = e instanceof Error ? e.message : 'token exchange failed';
58 return new NextResponse(htmlPage(`<h1>Token exchange failed</h1><div class="err">${msg}</div><a class="btn" href="/admin/pinterest">Back</a>`), {
59 status: 502, headers: { 'content-type': 'text/html; charset=utf-8' },
60 });
61 }
62
63 if (!tokens.refresh_token) {
64 return new NextResponse(htmlPage(`<h1>Connected, but no refresh token</h1><div class="err">Pinterest returned an access token but no refresh token. Re-run the connect flow and ensure all four scopes are granted.</div><a class="btn" href="/admin/pinterest">Back</a>`), {
65 status: 502, headers: { 'content-type': 'text/html; charset=utf-8' },
66 });
67 }
68
69 // Persist the refresh token to the integrations table so the lib can use
70 // it immediately. No more copy/paste into env required — Disconnect on
71 // /admin/pinterest wipes it from the same place.
72 try {
73 await saveRefreshToken(tokens.refresh_token);
74 } catch (e) {
75 const msg = e instanceof Error ? e.message : 'save failed';
76 return new NextResponse(htmlPage(`<h1>Token received but not saved</h1><div class="err">${msg}</div><a class="btn" href="/admin/pinterest">Back</a>`), {
77 status: 500, headers: { 'content-type': 'text/html; charset=utf-8' },
78 });
79 }
80
81 const expiresDays = tokens.refresh_token_expires_in
82 ? Math.round(tokens.refresh_token_expires_in / 86400)
83 : '~365';
84
85 const body = `
86 <h1>Pinterest connected ✓</h1>
87 <p>Your refresh token has been saved to the studio database — no env edits
88 required. It lasts about <strong>${expiresDays} days</strong>; reconnect
89 anytime via the <a href="/admin/pinterest">setup page</a>.</p>
90 <p>Granted scopes: <code>${tokens.scope || '(unknown)'}</code></p>
91 <p>The per-tile "Pin" action on <a href="/admin/images">/admin/images</a>
92 is now live.</p>
93 <a class="btn" href="/admin/pinterest">Back to setup</a>
94 `;
95
96 // Clear the OAuth state cookie now that it's been consumed.
97 const res = new NextResponse(htmlPage(body), { headers: { 'content-type': 'text/html; charset=utf-8' } });
98 res.cookies.set('pin_oauth_state', '', { path: '/', maxAge: 0 });
99 return res;
100}