Files
sam-portal/src/app/api/auth/route.ts
T
2026-09-09 16:20:24 -03:00

54 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { COOKIE, isAllowed, signSession, SESSION_MAX_AGE } from "@/lib/auth";
const API_URL =
process.env.NEXT_PUBLIC_API_URL || "https://api.devops.norteamericano.cl";
// Login IT: USUARIO = idUsuario. Valida en el backend
// (sige_sam_v3.usuario, plano o SHA256) y exige que el email
// retornado esté en IT_USERS (allowlist).
export async function POST(req: NextRequest) {
try {
const { idUsuario, email, password } = await req.json();
const id = String(idUsuario ?? email ?? "").trim();
if (!id || !password) {
return NextResponse.json({ error: "Faltan credenciales" }, { status: 400 });
}
let mail = "";
try {
const res = await fetch(`${API_URL}/api/Auth/it-login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ idUsuario: id, email: id, password: String(password) }),
cache: "no-store",
});
if (!res.ok) throw new Error("backend");
const j = await res.json();
mail = String(j?.user?.email || "").trim().toLowerCase();
} catch {
mail = "";
}
if (!mail || !isAllowed(mail)) {
await new Promise((r) => setTimeout(r, 600));
return NextResponse.json({ error: "Credenciales inválidas" }, { status: 401 });
}
const res = NextResponse.json({ ok: true, email: mail });
res.cookies.set(COOKIE, await signSession(mail), {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: SESSION_MAX_AGE,
});
return res;
} catch {
return NextResponse.json({ error: "Error interno" }, { status: 500 });
}
}
export async function DELETE() {
const res = NextResponse.json({ ok: true });
res.cookies.set(COOKIE, "", { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 0 });
return res;
}