cg / hackerproducts
64 files · 5,803 lines · 161.0 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.
Quick jump: page.tsxpage.tsxglobals.cssschema.sqlpackage.json
root / src / app / api / auth / register / route.ts
src/app/api/auth/register/route.ts · 118 lines · 4.1 KB← back to folder
| 1 | import crypto from "node:crypto"; |
| 2 | import { NextResponse } from "next/server"; |
| 3 | import { query } from "@/db"; |
| 4 | import { createSession, isConfiguredAdmin } from "@/lib/auth"; |
| 5 | import { checkAndRecordRateLimit, getHashedClientIp } from "@/lib/antispam"; |
| 6 | import { LIMITS } from "@/lib/limits"; |
| 7 | import { hashPassword } from "@/lib/password"; |
| 8 | import { isReservedUsername, sanitizeUsername } from "@/lib/validation"; |
| 9 | |
| 10 | const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; |
| 11 | |
| 12 | export async function POST(request: Request) { |
| 13 | const body = (await request.json().catch(() => null)) as { |
| 14 | username?: string; |
| 15 | email?: string; |
| 16 | password?: string; |
| 17 | website_confirm?: string; // honeypot |
| 18 | } | null; |
| 19 | |
| 20 | if (!body) { |
| 21 | return NextResponse.json({ error: "Invalid request body." }, { status: 400 }); |
| 22 | } |
| 23 | |
| 24 | if (body.website_confirm && body.website_confirm.trim().length > 0) { |
| 25 | return NextResponse.json({ error: "Registration rejected." }, { status: 400 }); |
| 26 | } |
| 27 | |
| 28 | // Rate limit registrations: max 3 new accounts per IP per 24 hours |
| 29 | const ipHash = getHashedClientIp(request); |
| 30 | const rl = await checkAndRecordRateLimit({ |
| 31 | action: "register", |
| 32 | key: ipHash, |
| 33 | maxCount: 3, |
| 34 | windowSeconds: 24 * 60 * 60, |
| 35 | }); |
| 36 | if (!rl.allowed) { |
| 37 | return NextResponse.json( |
| 38 | { error: "Too many accounts created from this network today. Please try again tomorrow." }, |
| 39 | { status: 429 } |
| 40 | ); |
| 41 | } |
| 42 | |
| 43 | const rawUsername = (body.username ?? "").trim(); |
| 44 | const username = sanitizeUsername(rawUsername); |
| 45 | if ( |
| 46 | !username || |
| 47 | username.length < LIMITS.usernameMin || |
| 48 | username.length > LIMITS.usernameMax || |
| 49 | username !== rawUsername.toLowerCase() |
| 50 | ) { |
| 51 | return NextResponse.json( |
| 52 | { |
| 53 | error: `Username must be ${LIMITS.usernameMin}–${LIMITS.usernameMax} lowercase letters, numbers, hyphens, or underscores.`, |
| 54 | }, |
| 55 | { status: 400 } |
| 56 | ); |
| 57 | } |
| 58 | if (isReservedUsername(username)) { |
| 59 | return NextResponse.json({ error: "That username is reserved." }, { status: 400 }); |
| 60 | } |
| 61 | |
| 62 | const email = (body.email ?? "").trim().toLowerCase(); |
| 63 | if (!EMAIL_RE.test(email) || email.length > 254) { |
| 64 | return NextResponse.json({ error: "Please enter a valid email address." }, { status: 400 }); |
| 65 | } |
| 66 | |
| 67 | const password = body.password ?? ""; |
| 68 | if (password.length < 8 || password.length > 128) { |
| 69 | return NextResponse.json( |
| 70 | { error: "Password must be between 8 and 128 characters." }, |
| 71 | { status: 400 } |
| 72 | ); |
| 73 | } |
| 74 | |
| 75 | // Optional: if Neon Auth is configured with a live URL, register there too (best-effort) |
| 76 | const neonAuthBase = process.env.NEON_AUTH_BASE_URL?.trim(); |
| 77 | if (neonAuthBase) { |
| 78 | await fetch(`${neonAuthBase.replace(/\/+$/, "")}/sign-up/email`, { |
| 79 | method: "POST", |
| 80 | headers: { "Content-Type": "application/json" }, |
| 81 | body: JSON.stringify({ email, password, name: username }), |
| 82 | }).catch(() => undefined); |
| 83 | } |
| 84 | |
| 85 | const existingProductSlug = await query( |
| 86 | `SELECT 1 FROM products WHERE LOWER(slug) = LOWER($1) LIMIT 1`, |
| 87 | [username] |
| 88 | ); |
| 89 | if (existingProductSlug.rowCount && existingProductSlug.rowCount > 0) { |
| 90 | return NextResponse.json({ error: "That username is already taken." }, { status: 409 }); |
| 91 | } |
| 92 | |
| 93 | const existingUser = await query<{ username: string; email: string | null }>( |
| 94 | `SELECT username, email FROM users WHERE LOWER(username) = LOWER($1) OR LOWER(email) = LOWER($2) LIMIT 1`, |
| 95 | [username, email] |
| 96 | ); |
| 97 | |
| 98 | if (existingUser.rows[0]) { |
| 99 | if (existingUser.rows[0].username.toLowerCase() === username.toLowerCase()) { |
| 100 | return NextResponse.json({ error: "That username is already taken." }, { status: 409 }); |
| 101 | } |
| 102 | return NextResponse.json({ error: "An account with that email already exists." }, { status: 409 }); |
| 103 | } |
| 104 | |
| 105 | const id = crypto.randomUUID(); |
| 106 | const passwordHash = hashPassword(password); |
| 107 | const isAdmin = isConfiguredAdmin(email, username); |
| 108 | |
| 109 | await query( |
| 110 | `INSERT INTO users (id, username, email, name, provider, provider_account_id, password_hash, is_admin) |
| 111 | VALUES ($1, $2, $3, $4, 'credentials', $3, $5, $6)`, |
| 112 | [id, username, email, username, passwordHash, isAdmin] |
| 113 | ); |
| 114 | |
| 115 | await createSession(id); |
| 116 | return NextResponse.json({ ok: true, user: { id, username, email } }, { status: 201 }); |
| 117 | } |
| 118 |