This commit is contained in:
eric
2026-03-12 19:54:58 -05:00
parent 14bbd3b306
commit f66859c032
31 changed files with 1132 additions and 312 deletions

View File

@@ -1,40 +1,26 @@
import { NextRequest, NextResponse } from "next/server";
import { getPocketBaseConfig } from "@/config/services.config";
import { getAdminToken } from "@/app/lib/pocketbase/admin";
const COOKIE_NAME = "pb_session";
import { COOKIE_NAME } from "@/app/lib/auth-cookie";
function getOrCreateUserId(request: NextRequest): string {
function getUserIdFromCookie(request: NextRequest): string | null {
const cookie = request.cookies.get(COOKIE_NAME)?.value;
if (cookie) {
try {
const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8"));
if (payload?.userId) return payload.userId;
} catch {
/* ignore */
}
if (!cookie) return null;
try {
const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8"));
return payload?.userId ?? null;
} catch {
return null;
}
return `user${Date.now()}`;
}
async function getAdminToken(): Promise<string | null> {
const email = process.env.POCKETBASE_EMAIL;
const password = process.env.POCKETBASE_PASSWORD;
if (!email || !password) return null;
const pb = getPocketBaseConfig();
const res = await fetch(`${pb.url}/api/admins/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity: email, password }),
});
if (!res.ok) return null;
const data = await res.json();
return data?.token ?? null;
}
export async function POST(request: NextRequest) {
try {
const userId = getOrCreateUserId(request);
const userId = getUserIdFromCookie(request);
if (!userId) {
return NextResponse.json({ ok: false, error: "请先登录" }, { status: 401 });
}
const body = await request.json();
const formData = body && typeof body === "object" ? body : {};
@@ -73,27 +59,55 @@ export async function POST(request: NextRequest) {
const pb = getPocketBaseConfig();
const collection = pb.joinCollection;
const base = pb.url.replace(/\/$/, "");
const doCreate = async (authToken?: string) => {
const doUpsert = async (authToken: string) => {
const headers: Record<string, string> = {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
};
if (authToken) headers["Authorization"] = authToken;
return fetch(`${pb.url}/api/collections/${collection}/records`, {
const filter = `user_id="${userId}"`;
const listRes = await fetch(
`${base}/api/collections/${collection}/records?filter=${encodeURIComponent(filter)}&perPage=1`,
{ headers: { Authorization: `Bearer ${authToken}` }, cache: "no-store" }
);
const listData = await listRes.json().catch(() => ({}));
const existing = (listData?.items ?? [])[0];
if (existing?.id) {
const patchBody: Record<string, string | number> = {
nickname: record.nickname,
occupation: record.occupation,
reason: record.reason,
single: record.single,
wechatId: record.wechatId,
gender: record.gender,
education: record.education,
gradYear: record.gradYear,
phone: record.phone,
};
if ("media" in record) patchBody.media = record.media as string;
return fetch(`${base}/api/collections/${collection}/records/${existing.id}`, {
method: "PATCH",
headers,
body: JSON.stringify(patchBody),
});
}
return fetch(`${base}/api/collections/${collection}/records`, {
method: "POST",
headers,
body: JSON.stringify(record),
});
};
let res = await doCreate();
if (res.status === 403) {
const token = await getAdminToken();
if (token) res = await doCreate(token);
const token = await getAdminToken();
if (!token) {
return NextResponse.json({ ok: false, error: "服务配置错误" }, { status: 500 });
}
const res = await doUpsert(token);
if (!res.ok) {
const errText = await res.text();
console.error("PocketBase create error:", res.status, errText);