// Author: Simon-Pierre Boucher // Contact: contact@spboucher.ai // Project: chat.spboucher.ai import { NextResponse, type NextRequest } from "next/server"; import { verifyCredentials, createSession, loginRateLimited, recordLoginAttempt, sessionCookieHeader, } from "@/lib/auth/auth"; import { clientIp } from "@/lib/auth/guard"; export const runtime = "nodejs"; export async function POST(req: NextRequest) { const ip = await clientIp(); if (loginRateLimited(ip)) { return NextResponse.json( { error: "Too many attempts. Wait 15 minutes and try again." }, { status: 429 } ); } let body: { username?: string; password?: string }; try { body = await req.json(); } catch { return NextResponse.json({ error: "Invalid request." }, { status: 400 }); } const username = String(body.username ?? "").trim(); const password = String(body.password ?? ""); if (!username || !password) { return NextResponse.json({ error: "Enter your username and password." }, { status: 400 }); } const user = await verifyCredentials(username, password); recordLoginAttempt(ip, Boolean(user)); if (!user) { return NextResponse.json({ error: "Wrong username or password." }, { status: 401 }); } const token = createSession(user.id, req.headers.get("user-agent") ?? undefined, ip); const res = NextResponse.json({ ok: true, username: user.username }); res.headers.set("Set-Cookie", sessionCookieHeader(token, 60 * 60 * 24 * 30)); return res; }