refactor(auth): centralize auth routing via proxy and marker cookie

This commit is contained in:
2026-06-10 12:47:47 +08:00
parent 1db3e3ae31
commit 2066934094
7 changed files with 156 additions and 38 deletions
+51
View File
@@ -0,0 +1,51 @@
/**
* 路由信号 cookie 管理端点
*
* 用途:写/清 `cozsweet_authed` httpOnly cookie,作为 `src/router/proxy.ts`
* 的"用户已登录"信号源。
*
* 与 `next-auth.session-token` 的区别:
* - NextAuth cookie 仅社交登录设置,邮箱登录不写入
* - 本端点由所有登录出口(社交 / 邮箱)统一调用,proxy 只需读这一个 cookie
*
* 调用方:
* - 社交登录出口(nextauth-helpers.persistBackendSession**server 端**直接用
* `next/headers.cookies()` 写,不走本端点)
* - 邮箱登录出口(auth-machine.emailLoginActor / emailRegisterThenLoginActor
* **client 端** fetch POST
* - 登出(nextauth-helpers.logoutclient 端 fetch DELETE
*
* 安全:cookie 设为 `HttpOnly` + `SameSite=Lax`prod 额外 `Secure`。
*/
import { NextResponse } from "next/server";
const COOKIE_NAME = "cozsweet_authed";
const ONE_WEEK = 60 * 60 * 24 * 7;
/** 设置 httpOnly 路由信号 cookie(任何登录成功后调用) */
export async function POST() {
const res = NextResponse.json({ ok: true });
res.cookies.set({
name: COOKIE_NAME,
value: "1",
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: ONE_WEEK,
});
return res;
}
/** 清除路由信号 cookie(登出时调用) */
export async function DELETE() {
const res = NextResponse.json({ ok: true });
res.cookies.set({
name: COOKIE_NAME,
value: "",
path: "/",
maxAge: 0,
});
return res;
}