Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SPB Private Cloud8 * File : app/api/auth/otp/verify/route.ts9 * Module : app10 * Repository : https://git.spboucher.ai/spb-cloud11 * Project Website : https://cloud.spboucher.ai12 * Created : 2026-09-0713 * Last Modified : 2026-09-0714 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { NextRequest, NextResponse } from "next/server";43import { getIronSession } from "iron-session";44import { timingSafeEqual } from "crypto";45import { SessionData, sessionOptions } from "@/lib/session";46import { prisma } from "@/lib/prisma";47import { checkLoginRateLimit } from "@/lib/rate-limit";48import { completeLogin, clientIp } from "@/lib/login-complete";49import { logActivity } from "@/lib/activity";50import { MAX_ATTEMPTS, hashCode } from "@/lib/otp";5152/** POST /api/auth/otp/verify { code } — valide le code envoyé par courriel et ouvre la session. */53export async function POST(request: NextRequest) {54 const ip = clientIp(request);55 if (!(await checkLoginRateLimit(ip))) {56 return NextResponse.json({ error: "Trop de tentatives. Réessayez dans 1 minute." }, { status: 429 });57 }58 const body = await request.json().catch(() => ({}));59 const code = String(body?.code ?? "").replace(/\D/g, "");6061 const response = NextResponse.json({ success: true });62 const session = await getIronSession<SessionData>(request, response, sessionOptions);63 const otp = session.otp;6465 if (!otp) return NextResponse.json({ error: "Aucun code en attente. Demandez un nouveau code." }, { status: 400 });66 if (Date.now() > otp.expiresAt) {67 session.otp = undefined; await session.save();68 return NextResponse.json({ error: "Code expiré. Demandez un nouveau code." }, { status: 410 });69 }70 if (code.length !== 6) return NextResponse.json({ error: "Le code comporte 6 chiffres." }, { status: 400 });7172 const expected = Buffer.from(otp.hash, "hex");73 const given = Buffer.from(hashCode(code, otp.salt), "hex");74 const valid = expected.length === given.length && timingSafeEqual(expected, given);7576 if (!valid) {77 otp.attempts += 1;78 if (otp.attempts >= MAX_ATTEMPTS) {79 session.otp = undefined; await session.save();80 await logActivity("LOGIN_CODE_LOCKED", null, `Code invalidé après ${MAX_ATTEMPTS} essais (${otp.email}, ${ip})`);81 return NextResponse.json({ error: "Trop d'essais : le code a été invalidé. Demandez un nouveau code." }, { status: 423 });82 }83 session.otp = otp; await session.save();84 return NextResponse.json({ error: `Code incorrect (${MAX_ATTEMPTS - otp.attempts} essai${MAX_ATTEMPTS - otp.attempts > 1 ? "s" : ""} restant${MAX_ATTEMPTS - otp.attempts > 1 ? "s" : ""}).` }, { status: 401 });85 }8687 const user = await prisma.user.findUnique({ where: { id: otp.userId }, select: { id: true, role: true, email: true } });88 if (!user || (user.email ?? "").trim().toLowerCase() !== otp.email) {89 session.otp = undefined; await session.save();90 return NextResponse.json({ error: "Compte introuvable." }, { status: 404 });91 }9293 const done = await completeLogin(request, session, user, "email_code");94 if (!done.ok) return NextResponse.json({ error: done.error }, { status: done.status });95 return response;96}97