42 lines
1.8 KiB
TypeScript
42 lines
1.8 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { cookies } from "next/headers";
|
|
import { getSessionCookieName, getSessionTtlMs } from "@/lib/server/auth";
|
|
import { registerUser } from "@/lib/server/auth-service";
|
|
import { enforceAuthRateLimit } from "@/lib/server/rate-limit";
|
|
import { toErrorResponse } from "@/lib/server/errors";
|
|
import { getRequestMeta } from "@/lib/server/request";
|
|
|
|
export async function POST(req: Request) {
|
|
const { requestId, ip } = await getRequestMeta();
|
|
const body = await req.json().catch(() => null);
|
|
const email = String(body?.email || "").trim().toLowerCase();
|
|
const password = String(body?.password || "");
|
|
const displayName = String(body?.displayName || "").trim();
|
|
|
|
let user;
|
|
let session;
|
|
try {
|
|
await enforceAuthRateLimit({ route: "register", ip, identifier: email });
|
|
if (!email || !email.includes("@"))
|
|
return NextResponse.json({ requestId, request_id: requestId, error: { code: "INVALID_EMAIL", message: "Invalid email" } }, { status: 400 });
|
|
if (password.length < 8)
|
|
return NextResponse.json({ requestId, request_id: requestId, error: { code: "PASSWORD_TOO_SHORT", message: "Password too short" } }, { status: 400 });
|
|
const result = await registerUser({ email, password, displayName });
|
|
user = result.user;
|
|
session = result.session;
|
|
} catch (e) {
|
|
const { status, body } = toErrorResponse(e, "POST /api/auth/register", requestId);
|
|
return NextResponse.json(body, { status });
|
|
}
|
|
const cookieStore = await cookies();
|
|
cookieStore.set(getSessionCookieName(), session.token, {
|
|
httpOnly: true,
|
|
sameSite: "lax",
|
|
secure: process.env.NODE_ENV === "production",
|
|
maxAge: Math.floor(getSessionTtlMs() / 1000),
|
|
path: "/"
|
|
});
|
|
|
|
return NextResponse.json({ requestId, request_id: requestId, user });
|
|
}
|