/** * /api/admin/login — 后台登录。 * POST { username, password } → 设置 httpOnly 会话 cookie。 */ import { NextResponse } from "next/server"; import { createSession, SESSION_COOKIE } from "@/lib/auth"; import { verifyAdminPassword } from "@/lib/auth"; export const runtime = "nodejs"; export async function POST(req: Request) { let body: { username?: string; password?: string }; try { body = await req.json(); } catch { return NextResponse.json({ error: "请求格式错误" }, { status: 400 }); } const username = String(body.username ?? "").trim(); const password = String(body.password ?? ""); if (!username || !password) { return NextResponse.json({ error: "请输入用户名和密码" }, { status: 400 }); } const userId = verifyAdminPassword(username, password); if (userId === null) { // 统一错误信息,不区分用户名/密码错误(防枚举) return NextResponse.json({ error: "用户名或密码不正确" }, { status: 401 }); } const { token, csrf } = createSession(userId); const res = NextResponse.json({ ok: true, csrf }); res.cookies.set(SESSION_COOKIE, token, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: 60 * 60 * 24 * 7, }); return res; }