This commit is contained in:
eric
2026-03-12 19:50:25 -05:00
parent ffa5043daf
commit 37d0883ce9
22 changed files with 688 additions and 236 deletions

View File

@@ -1,13 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { getPocketBaseConfig } from "@/config/services.config";
import { getAuthCookieDomain } from "@/config/domain.config";
const COOKIE_NAME = "pb_session";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
export async function GET(request: NextRequest) {
const cookie = request.cookies.get(COOKIE_NAME)?.value;
const domain = getAuthCookieDomain(request);
if (!cookie) {
return NextResponse.json({ ok: true, user: null });
}
@@ -17,18 +13,18 @@ export async function GET(request: NextRequest) {
if (!token || !userId) return NextResponse.json({ ok: true, user: null });
const pb = getPocketBaseConfig();
const res = await fetch(`${pb.url}/api/users/refresh`, {
const res = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/auth-refresh`, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
const r = NextResponse.json({ ok: true, user: null });
r.cookies.set(COOKIE_NAME, "", { ...(domain && { domain }), path: "/", maxAge: 0 });
r.cookies.set(COOKIE_NAME, "", getCookieOptions(true, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return r;
}
const data = await res.json();
const newToken = data.token;
const newRecord = data.record;
// 刷新成功:回写新 token 到 Cookie保持登录态长期有效
if (newToken && newRecord?.id) {
const newPayload = JSON.stringify({
token: newToken,
@@ -41,14 +37,7 @@ export async function GET(request: NextRequest) {
user: { id: newRecord.id, email: newRecord.email ?? email },
token: newToken,
});
r.cookies.set(COOKIE_NAME, encoded, {
...(domain && { domain }),
path: "/",
maxAge: COOKIE_MAX_AGE,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
httpOnly: true,
});
r.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return r;
}
return NextResponse.json({