nova-store/app/api/register/route.js
2026-07-27 08:31:07 -06:00

28 lines
1.3 KiB
JavaScript

import { NextResponse } from "next/server";
import db from "../../lib/db";
import { hashPassword, signSession } from "../../lib/auth";
export async function POST(req) {
let body;
try { body = await req.json(); } catch { return NextResponse.json({ error: "Solicitud inválida" }, { status: 400 }); }
const name = (body.name || "").trim();
const email = (body.email || "").trim().toLowerCase();
const password = body.password || "";
if (!email || !password) return NextResponse.json({ error: "Email y contraseña son obligatorios" }, { status: 400 });
if (password.length < 6) return NextResponse.json({ error: "La contraseña debe tener al menos 6 caracteres" }, { status: 400 });
try {
const info = db.prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)")
.run(name, email, hashPassword(password));
const res = NextResponse.json({ ok: true, user: { id: Number(info.lastInsertRowid), name, email } });
res.cookies.set("session", signSession(info.lastInsertRowid), {
httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 7,
});
return res;
} catch (e) {
if (String(e).includes("UNIQUE")) return NextResponse.json({ error: "Ese email ya está registrado" }, { status: 409 });
return NextResponse.json({ error: "No se pudo crear la cuenta" }, { status: 500 });
}
}