cg / hackerproducts

64 files · 5,803 lines · 161.0 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.

Quick jump: page.tsx / page.tsx / globals.css / schema.sql / package.json

root / src / app / api / auth / login / route.ts

src/app/api/auth/login/route.ts · 80 lines · 2.6 KB← back to folder
1import { NextResponse } from "next/server";
2import { query } from "@/db";
3import { createSession, upsertOAuthUser } from "@/lib/auth";
4import { verifyPassword } from "@/lib/password";
5
6export async function POST(request: Request) {
7 const body = (await request.json().catch(() => null)) as {
8 identifier?: string;
9 password?: string;
10 } | null;
11
12 if (!body) {
13 return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
14 }
15
16 const identifier = (body.identifier ?? "").trim().toLowerCase();
17 const password = body.password ?? "";
18 if (!identifier || !password) {
19 return NextResponse.json(
20 { error: "Please enter your email or username and password." },
21 { status: 400 }
22 );
23 }
24
25 const res = await query<{
26 id: string;
27 username: string;
28 email: string | null;
29 password_hash: string | null;
30 }>(
31 `SELECT id, username, email, password_hash
32 FROM users
33 WHERE LOWER(email) = $1 OR LOWER(username) = $1
34 LIMIT 1`,
35 [identifier]
36 );
37
38 const user = res.rows[0];
39 if (user && verifyPassword(password, user.password_hash)) {
40 await createSession(user.id);
41 return NextResponse.json({ ok: true, user: { id: user.id, username: user.username } });
42 }
43
44 // Fallback: if Neon Auth is configured with a live URL, verify against Neon Auth
45 const neonAuthBase = process.env.NEON_AUTH_BASE_URL?.trim();
46 if (neonAuthBase && identifier.includes("@")) {
47 try {
48 const neonRes = await fetch(`${neonAuthBase.replace(/\/+$/, "")}/sign-in/email`, {
49 method: "POST",
50 headers: { "Content-Type": "application/json" },
51 body: JSON.stringify({ email: identifier, password }),
52 });
53 if (neonRes.ok) {
54 const data = (await neonRes.json()) as {
55 user?: { id?: string; email?: string; name?: string; image?: string | null };
56 };
57 if (data.user?.email) {
58 const synced = await upsertOAuthUser({
59 provider: "credentials" as unknown as "github",
60 providerAccountId: data.user.id || data.user.email.toLowerCase(),
61 email: data.user.email.toLowerCase(),
62 name: data.user.name ?? null,
63 preferredUsername: data.user.name || data.user.email.split("@")[0],
64 avatarUrl: data.user.image ?? null,
65 });
66 await createSession(synced.id);
67 return NextResponse.json({
68 ok: true,
69 user: { id: synced.id, username: synced.username },
70 });
71 }
72 }
73 } catch {
74 // Fall through to invalid credentials
75 }
76 }
77
78 return NextResponse.json({ error: "Invalid email/username or password." }, { status: 401 });
79}
80
cg / hackerproducts — hacker products