import { NextResponse, type NextRequest } from "next/server"; import { z } from "zod"; import { prisma } from "@/lib/prisma"; import { verifyPin, isValidPin } from "@/lib/password"; import { createSession } from "@/lib/session"; import { env } from "@/lib/env"; import { audit } from "@/lib/audit"; import { clientIp, userAgent } from "@/lib/request"; const Body = z.object({ operatorId: z.string().min(1), pin: z.string().regex(/^\d{4}$/, "PIN must be 4 digits"), }); export async function POST(req: NextRequest) { const parsed = Body.safeParse(await req.json().catch(() => ({}))); if (!parsed.success) { return NextResponse.json({ error: "Invalid PIN" }, { status: 400 }); } const { operatorId, pin } = parsed.data; if (!isValidPin(pin)) { return NextResponse.json({ error: "Invalid PIN" }, { status: 400 }); } const ip = clientIp(req); const ua = userAgent(req); const user = await prisma.user.findUnique({ where: { id: operatorId } }); if (!user || user.role !== "operator" || !user.active || !user.pinHash) { await audit({ action: "login_failed", entity: "User", entityId: user?.id, ipAddress: ip }); return NextResponse.json({ error: "Invalid PIN" }, { status: 401 }); } if (user.lockedUntil && user.lockedUntil.getTime() > Date.now()) { const mins = Math.ceil((user.lockedUntil.getTime() - Date.now()) / 60000); return NextResponse.json( { error: `Account locked. Try again in ${mins} minute${mins === 1 ? "" : "s"}.` }, { status: 423 }, ); } const ok = await verifyPin(pin, user.pinHash); if (!ok) { const attempts = user.failedAttempts + 1; const shouldLock = attempts >= env.PIN_MAX_ATTEMPTS; await prisma.user.update({ where: { id: user.id }, data: { failedAttempts: shouldLock ? 0 : attempts, lockedUntil: shouldLock ? new Date(Date.now() + env.PIN_LOCKOUT_MINUTES * 60_000) : null, }, }); await audit({ action: "login_failed", entity: "User", entityId: user.id, ipAddress: ip }); return NextResponse.json( { error: shouldLock ? `Too many attempts. Locked for ${env.PIN_LOCKOUT_MINUTES} minutes.` : "Invalid PIN", }, { status: shouldLock ? 423 : 401 }, ); } await createSession({ userId: user.id, role: "operator", userAgent: ua, ipAddress: ip, }); await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), failedAttempts: 0, lockedUntil: null }, }); await audit({ actorId: user.id, action: "login", entity: "User", entityId: user.id, ipAddress: ip }); return NextResponse.json({ ok: true, redirect: "/op" }); }