// Auteur : Simon-Pierre Boucher — contact@spboucher.ai import { NextRequest, NextResponse } from "next/server"; import { db, findUserByEmail, ensureKaId, touchLastLogin } from "@/lib/db"; import { ROLES } from "@/lib/roles"; import { hashPassword, mintSessionToken, SESSION_COOKIE, sessionCookieOptions, } from "@/lib/auth"; const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; export async function POST(req: NextRequest) { let body: { email?: string; password?: string; name?: string; role?: string; }; try { body = await req.json(); } catch { return NextResponse.json({ error: "Requête invalide." }, { status: 400 }); } const email = (body.email ?? "").trim().toLowerCase(); const password = body.password ?? ""; const name = (body.name ?? "").trim(); if (!EMAIL_RE.test(email)) return NextResponse.json( { error: "Adresse courriel invalide." }, { status: 400 }, ); if (password.length < 8) return NextResponse.json( { error: "Le mot de passe doit compter au moins 8 caractères." }, { status: 400 }, ); if (name.length < 2) return NextResponse.json( { error: "Dites-nous au moins votre prénom." }, { status: 400 }, ); const role = body.role ?? ""; if (!ROLES[role]) return NextResponse.json( { error: "Choisissez votre type de compte (utilisateur, fournisseur ou équipe)." }, { status: 400 }, ); if (findUserByEmail(email)) return NextResponse.json( { error: "Cette adresse a déjà un KA ID — connectez-vous (ou utilisez « Continuer avec Google » si le compte vient de Google).", }, { status: 409 }, ); const info = db .prepare( "INSERT INTO users (email, name, password_hash, role) VALUES (?, ?, ?, ?)", ) .run(email, name, hashPassword(password), role); ensureKaId(Number(info.lastInsertRowid)); touchLastLogin(Number(info.lastInsertRowid)); const res = NextResponse.json({ ok: true }); res.cookies.set( SESSION_COOKIE, await mintSessionToken(Number(info.lastInsertRowid)), sessionCookieOptions, ); return res; }