Lumen & Gesso / website · lumengesso.com / app / lib / lumen-auth.ts
| 1 | import 'server-only'; |
| 2 | import { getCloudflareContext } from '@opennextjs/cloudflare'; |
| 3 | import { headers } from 'next/headers'; |
| 4 | import { env } from './env'; |
| 5 | import { sendEmail } from './email'; |
| 6 | import { createD1Auth, type AuthDatabase, type SendLink } from './d1-auth'; |
| 7 | |
| 8 | type Customer = { id: string; email?: string; name?: string }; |
| 9 | |
| 10 | function authDatabase() { |
| 11 | const { COMMERCE_DB } = getCloudflareContext().env as { COMMERCE_DB?: AuthDatabase }; |
| 12 | if (!COMMERCE_DB) throw new Error('Lumen authentication database is missing.'); |
| 13 | return COMMERCE_DB; |
| 14 | } |
| 15 | |
| 16 | export function authOrigin() { |
| 17 | return new URL(process.env.LUMEN_AUTH_ORIGIN || env.site.url()).origin; |
| 18 | } |
| 19 | |
| 20 | async function deliverLink({ email, url }: Parameters<SendLink>[0]) { |
| 21 | const safeUrl = url.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>'); |
| 22 | await sendEmail({ |
| 23 | to: email, |
| 24 | subject: 'Your private Lumen & Gesso link', |
| 25 | html: `<p>Open your private link to see your commissions, then save a passkey to get back any time.</p><p><a href="${safeUrl}">Open Lumen & Gesso</a></p><p>This link expires in 15 minutes. You can ignore this message if you didn’t request it.</p>`, |
| 26 | text: `Your private Lumen & Gesso link: ${url}\n\nThis link expires in 15 minutes.`, |
| 27 | }); |
| 28 | } |
| 29 | |
| 30 | export function lumenAuth(sendMagicLink: SendLink = deliverLink) { |
| 31 | const secret = process.env.LUMENGESSO_BETTER_AUTH_SECRET; |
| 32 | if (!secret || secret.length < 32) throw new Error('Lumen authentication signing secret is missing.'); |
| 33 | const origin = authOrigin(); |
| 34 | return createD1Auth(authDatabase(), origin, secret, sendMagicLink); |
| 35 | } |
| 36 | |
| 37 | export async function getCustomerUser(): Promise<Customer | null> { |
| 38 | const requestHeaders = await headers(); |
| 39 | if (!/(?:^|;\s*)(?:__Secure-)?lumen\.session_token=/.test(requestHeaders.get('cookie') ?? '')) return null; |
| 40 | const session = await lumenAuth().api.getSession({ headers: requestHeaders }); |
| 41 | return session?.user.emailVerified ? session.user : null; |
| 42 | } |
| 43 | |
| 44 | export async function provisionCustomer(email: string): Promise<string> { |
| 45 | const now = new Date().toISOString(); |
| 46 | const db = authDatabase(); |
| 47 | const inserted = await db.prepare(` |
| 48 | INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt") |
| 49 | VALUES (?, '', ?, 0, ?, ?) ON CONFLICT (email) DO NOTHING RETURNING id |
| 50 | `).bind(crypto.randomUUID(), email, now, now).first<{ id: string }>(); |
| 51 | if (inserted) return inserted.id; |
| 52 | const existing = await db.prepare('SELECT id FROM "user" WHERE email=?').bind(email).first<{ id: string }>(); |
| 53 | if (!existing) throw new Error('Could not find or create the customer account.'); |
| 54 | return existing.id; |
| 55 | } |
| 56 | |
| 57 | export async function customerDetailsById(userId: string) { |
| 58 | return authDatabase().prepare('SELECT name FROM "user" WHERE id=?').bind(userId).first<{ name: string }>(); |
| 59 | } |
| 60 | |
| 61 | export async function hasBetterAuthCustomer(email: string) { |
| 62 | return Boolean(await authDatabase().prepare('SELECT id FROM "user" WHERE email=?') |
| 63 | .bind(email).first<{ id: string }>()); |
| 64 | } |