's'
This commit is contained in:
19
app/api/auth/email/route.ts
Normal file
19
app/api/auth/email/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* 从 Cookie 读取邮箱(不调用 PB),用于 emailLinked=1 但 userName 被覆盖的场景
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { COOKIE_NAME } from "@/app/lib/auth-cookie";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const cookie = request.cookies.get(COOKIE_NAME)?.value;
|
||||
if (!cookie) {
|
||||
return NextResponse.json({ ok: true, email: null });
|
||||
}
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8"));
|
||||
const email = payload?.email ?? null;
|
||||
return NextResponse.json({ ok: true, email: typeof email === "string" ? email : null });
|
||||
} catch {
|
||||
return NextResponse.json({ ok: true, email: null });
|
||||
}
|
||||
}
|
||||
@@ -1,148 +1,138 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPocketBaseConfig, SITE_ID } from "@/config/services.config";
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
import {
|
||||
ensureSiteVipForUser,
|
||||
getAdminToken,
|
||||
isAnonymousUserId,
|
||||
upsertVipEmailLink,
|
||||
} from "@/app/api/vip/_helpers";
|
||||
|
||||
async function getAdminToken(): Promise<string | null> {
|
||||
const email = process.env.POCKETBASE_EMAIL;
|
||||
const password = process.env.POCKETBASE_PASSWORD;
|
||||
if (!email || !password) return null;
|
||||
const DEFAULT_PASSWORD = "12345678";
|
||||
|
||||
type PBAuthRecord = {
|
||||
id: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
async function registerOrLoginUser(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<{ token: string; record: PBAuthRecord } | null> {
|
||||
const pb = getPocketBaseConfig();
|
||||
const res = await fetch(`${pb.url}/api/admins/auth-with-password`, {
|
||||
|
||||
await fetch(`${pb.url}/api/collections/users/records`, {
|
||||
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;
|
||||
}
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password,
|
||||
passwordConfirm: password,
|
||||
}),
|
||||
cache: "no-store",
|
||||
}).catch(() => null);
|
||||
|
||||
/** 将匿名 user_id 的支付记录关联到新创建的 PB 用户 */
|
||||
async function linkPaymentsToUser(
|
||||
adminToken: string,
|
||||
fromUserId: string,
|
||||
toUserId: string
|
||||
): Promise<void> {
|
||||
const pb = getPocketBaseConfig();
|
||||
const filter = `user_id = "${fromUserId}"`;
|
||||
const res = await fetch(
|
||||
`${pb.url}/api/collections/payments/records?filter=${encodeURIComponent(filter)}&perPage=500`,
|
||||
{ headers: { Authorization: `Bearer ${adminToken}` } }
|
||||
const loginRes = await fetch(
|
||||
`${pb.url}/api/collections/users/auth-with-password`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const items = data?.items ?? [];
|
||||
for (const item of items) {
|
||||
await fetch(`${pb.url}/api/collections/payments/records/${item.id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify({ user_id: toUserId }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function linkSiteVipToUser(
|
||||
adminToken: string,
|
||||
fromUserId: string,
|
||||
toUserId: string
|
||||
): Promise<void> {
|
||||
const pb = getPocketBaseConfig();
|
||||
const filter = `user_id = "${fromUserId}" && site_id = "${SITE_ID}"`;
|
||||
const res = await fetch(
|
||||
`${pb.url}/api/collections/site_vip/records?filter=${encodeURIComponent(filter)}&perPage=500`,
|
||||
{ headers: { Authorization: `Bearer ${adminToken}` } }
|
||||
);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const items = data?.items ?? [];
|
||||
for (const item of items) {
|
||||
await fetch(`${pb.url}/api/collections/site_vip/records/${item.id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify({ user_id: toUserId }),
|
||||
});
|
||||
if (!loginRes.ok) {
|
||||
const error = await loginRes.json().catch(() => ({}));
|
||||
throw new Error(error?.message || "邮箱或密码错误");
|
||||
}
|
||||
|
||||
const loginData = await loginRes.json().catch(() => ({}));
|
||||
if (!loginData?.token || !loginData?.record?.id) {
|
||||
throw new Error("邮箱绑定失败");
|
||||
}
|
||||
|
||||
return {
|
||||
token: loginData.token,
|
||||
record: loginData.record,
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const email = String(body?.email ?? "").trim();
|
||||
const password = String(body?.password ?? "").trim();
|
||||
const email = String(body?.email ?? "").trim().toLowerCase();
|
||||
const password = String(body?.password ?? "").trim() || DEFAULT_PASSWORD;
|
||||
const anonymousUserId = String(body?.anonymousUserId ?? "").trim();
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json({ ok: false, error: "请填写邮箱和密码" }, { status: 400 });
|
||||
}
|
||||
if (!anonymousUserId || !anonymousUserId.startsWith("user")) {
|
||||
return NextResponse.json({ ok: false, error: "无效的匿名用户ID" }, { status: 400 });
|
||||
}
|
||||
if (password.length < 8) {
|
||||
return NextResponse.json({ ok: false, error: "密码至少 8 位" }, { status: 400 });
|
||||
}
|
||||
console.log(
|
||||
"[link-email] request email=%s anonymousUserId=%s",
|
||||
email || "(empty)",
|
||||
anonymousUserId || "(empty)"
|
||||
);
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
|
||||
// 1. 尝试注册,若已存在则登录
|
||||
let token: string;
|
||||
let record: { id: string; email?: string };
|
||||
try {
|
||||
const registerRes = await fetch(`${pb.url}/api/collections/users/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password, passwordConfirm: password }),
|
||||
});
|
||||
if (registerRes.ok) {
|
||||
const regData = await registerRes.json();
|
||||
const loginRes = await fetch(`${pb.url}/api/collections/users/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
});
|
||||
if (!loginRes.ok) throw new Error("登录失败");
|
||||
const loginData = await loginRes.json();
|
||||
token = loginData.token;
|
||||
record = loginData.record;
|
||||
} else {
|
||||
const loginRes = await fetch(`${pb.url}/api/collections/users/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
});
|
||||
if (!loginRes.ok) {
|
||||
const err = await loginRes.json().catch(() => ({}));
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: err?.message || "邮箱或密码错误" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
const loginData = await loginRes.json();
|
||||
token = loginData.token;
|
||||
record = loginData.record;
|
||||
}
|
||||
} catch (e) {
|
||||
if (!email) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: e instanceof Error ? e.message : "注册/登录失败" },
|
||||
{ status: 500 }
|
||||
{ ok: false, error: "请填写邮箱" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const newUserId = record.id;
|
||||
|
||||
// 2. 用管理员 token 将 payments、site_vip 的 user_id 从匿名改为新用户
|
||||
const adminToken = await getAdminToken();
|
||||
if (adminToken) {
|
||||
await linkPaymentsToUser(adminToken, anonymousUserId, newUserId);
|
||||
await linkSiteVipToUser(adminToken, anonymousUserId, newUserId);
|
||||
if (!isAnonymousUserId(anonymousUserId)) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "无效的匿名 user_id" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
token,
|
||||
record: { id: record.id, email: record.email },
|
||||
});
|
||||
try {
|
||||
const authData = await registerOrLoginUser(email, password);
|
||||
if (!authData) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "邮箱绑定失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
const adminToken = await getAdminToken();
|
||||
if (!adminToken) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "PocketBase 管理员认证失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
await ensureSiteVipForUser(adminToken, anonymousUserId, authData.record.id);
|
||||
await upsertVipEmailLink(
|
||||
adminToken,
|
||||
email,
|
||||
authData.record.id,
|
||||
anonymousUserId
|
||||
);
|
||||
|
||||
console.log(
|
||||
"[link-email] success email=%s pbUserId=%s anonymousUserId=%s",
|
||||
email,
|
||||
authData.record.id,
|
||||
anonymousUserId
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
token: authData.token,
|
||||
record: {
|
||||
id: authData.record.id,
|
||||
email: authData.record.email ?? email,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[link-email] failed:", error);
|
||||
const message = error instanceof Error ? error.message : "邮箱绑定失败";
|
||||
const status = message.includes("密码") || message.includes("邮箱") ? 401 : 500;
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: message,
|
||||
},
|
||||
{ status }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,23 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
|
||||
|
||||
const ANONYMOUS_USER_COOKIE_NAME = "nomadvip_anon_uid";
|
||||
const PAY_ORDER_COOKIE_NAME = "nomadvip_pay_order";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(COOKIE_NAME, "", getCookieOptions(true, getHostFromRequest(request)) as Record<string, string | number | boolean>);
|
||||
const options = getCookieOptions(true, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>;
|
||||
res.cookies.set(COOKIE_NAME, "", options);
|
||||
res.cookies.set(ANONYMOUS_USER_COOKIE_NAME, "", {
|
||||
...options,
|
||||
httpOnly: false,
|
||||
});
|
||||
res.cookies.set(PAY_ORDER_COOKIE_NAME, "", {
|
||||
...options,
|
||||
httpOnly: false,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -1,48 +1,98 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
|
||||
import {
|
||||
COOKIE_NAME,
|
||||
getCookieOptions,
|
||||
getHostFromRequest,
|
||||
} from "@/app/lib/auth-cookie";
|
||||
|
||||
function normalizeAnonymousUserId(value: unknown): string | undefined {
|
||||
return typeof value === "string" && /^user\d+$/.test(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const cookie = request.cookies.get(COOKIE_NAME)?.value;
|
||||
if (!cookie) {
|
||||
return NextResponse.json({ ok: true, user: null });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8"));
|
||||
const { token, userId, email } = payload;
|
||||
if (!token || !userId) return NextResponse.json({ ok: true, user: null });
|
||||
const { token, userId, email, anonymousUserId } = payload;
|
||||
const normalizedAnonymousUserId = normalizeAnonymousUserId(anonymousUserId);
|
||||
|
||||
if (!token || !userId) {
|
||||
return NextResponse.json({ ok: true, user: null });
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const res = await fetch(`${pb.url}/api/collections/users/auth-refresh`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const r = NextResponse.json({ ok: true, user: null });
|
||||
r.cookies.set(COOKIE_NAME, "", getCookieOptions(true, getHostFromRequest(request)) as Record<string, string | number | boolean>);
|
||||
return r;
|
||||
const response = NextResponse.json({ ok: true, user: null });
|
||||
response.cookies.set(
|
||||
COOKIE_NAME,
|
||||
"",
|
||||
getCookieOptions(true, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const newToken = data.token;
|
||||
const newRecord = data.record;
|
||||
|
||||
if (newToken && newRecord?.id) {
|
||||
const newPayload = JSON.stringify({
|
||||
const nextPayload: Record<string, string> = {
|
||||
token: newToken,
|
||||
userId: newRecord.id,
|
||||
email: newRecord.email ?? email,
|
||||
});
|
||||
const encoded = Buffer.from(newPayload, "utf-8").toString("base64url");
|
||||
const r = NextResponse.json({
|
||||
};
|
||||
|
||||
if (normalizedAnonymousUserId) {
|
||||
nextPayload.anonymousUserId = normalizedAnonymousUserId;
|
||||
}
|
||||
|
||||
const encoded = Buffer.from(JSON.stringify(nextPayload), "utf-8").toString(
|
||||
"base64url"
|
||||
);
|
||||
|
||||
const response = NextResponse.json({
|
||||
ok: true,
|
||||
user: { id: newRecord.id, email: newRecord.email ?? email },
|
||||
user: {
|
||||
id: newRecord.id,
|
||||
email: newRecord.email ?? email,
|
||||
anonymousUserId: normalizedAnonymousUserId,
|
||||
},
|
||||
token: newToken,
|
||||
});
|
||||
r.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
|
||||
return r;
|
||||
|
||||
response.cookies.set(
|
||||
COOKIE_NAME,
|
||||
encoded,
|
||||
getCookieOptions(false, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
user: { id: data.record?.id ?? userId, email: data.record?.email ?? email },
|
||||
user: {
|
||||
id: data.record?.id ?? userId,
|
||||
email: data.record?.email ?? email,
|
||||
anonymousUserId: normalizedAnonymousUserId,
|
||||
},
|
||||
token: data.token,
|
||||
});
|
||||
} catch {
|
||||
|
||||
125
app/api/auth/store-email-link/route.ts
Normal file
125
app/api/auth/store-email-link/route.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 支付成功后存储 email -> user_id 映射,供「已有账号登录」按邮箱查库
|
||||
* 同时创建 PB 用户(邮箱+12345678),以便后续用邮箱+密码登录
|
||||
* 需 PocketBase 存在 vip_email_link 集合(email, user_id)
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
|
||||
const VIP_EMAIL_LINK_COLLECTION = "vip_email_link";
|
||||
const DEFAULT_PASSWORD = "12345678";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** 若 PB 无该邮箱用户则创建(密码 12345678),供后续邮箱登录 */
|
||||
async function ensurePbUserExists(pbUrl: string, email: string): Promise<void> {
|
||||
const registerRes = await fetch(`${pbUrl}/api/collections/users/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password: DEFAULT_PASSWORD,
|
||||
passwordConfirm: DEFAULT_PASSWORD,
|
||||
}),
|
||||
});
|
||||
if (registerRes.ok) {
|
||||
console.log("[store-email-link] 已创建 PB 用户 email=%s", email);
|
||||
return;
|
||||
}
|
||||
const err = await registerRes.json().catch(() => ({}));
|
||||
const alreadyExists =
|
||||
err?.data?.email?.message?.includes("unique") ||
|
||||
err?.message?.toLowerCase?.().includes("already") ||
|
||||
err?.message?.toLowerCase?.().includes("unique");
|
||||
if (alreadyExists) {
|
||||
console.log("[store-email-link] PB 用户已存在 email=%s", email);
|
||||
return;
|
||||
}
|
||||
console.warn("[store-email-link] 创建 PB 用户失败 email=%s status=%s", email, registerRes.status, err);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const email = String(body?.email ?? "").trim().toLowerCase();
|
||||
const userId = String(body?.user_id ?? body?.userId ?? "").trim();
|
||||
|
||||
console.log("[store-email-link] 请求 email=%s user_id=%s", email || "(空)", userId || "(空)");
|
||||
|
||||
if (!email || !userId) {
|
||||
return NextResponse.json({ ok: false, error: "请填写邮箱" }, { status: 400 });
|
||||
}
|
||||
|
||||
const adminToken = await getAdminToken();
|
||||
if (!adminToken) {
|
||||
return NextResponse.json({ ok: false, error: "服务未配置" }, { status: 500 });
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
try {
|
||||
await ensurePbUserExists(pb.url, email);
|
||||
} catch (e) {
|
||||
console.warn("[store-email-link] ensurePbUserExists 异常:", e);
|
||||
}
|
||||
|
||||
const safeEmail = email.replace(/"/g, '\\"');
|
||||
const filter = `email = "${safeEmail}"`;
|
||||
try {
|
||||
const listRes = await fetch(
|
||||
`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records?filter=${encodeURIComponent(filter)}&perPage=1`,
|
||||
{ headers: { Authorization: `Bearer ${adminToken}` } }
|
||||
);
|
||||
if (!listRes.ok) {
|
||||
return NextResponse.json({ ok: false, error: "vip_email_link 集合不存在,请在 PocketBase 中创建" }, { status: 500 });
|
||||
}
|
||||
const listData = await listRes.json().catch(() => ({}));
|
||||
const items = listData?.items ?? [];
|
||||
const recordBody: Record<string, string> = { email, user_id: userId };
|
||||
if (/^user\d+$/.test(userId)) {
|
||||
recordBody.anonymous_user_id = userId;
|
||||
}
|
||||
if (items.length > 0) {
|
||||
await fetch(`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records/${items[0].id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify(recordBody),
|
||||
});
|
||||
} else {
|
||||
const createRes = await fetch(`${pb.url}/api/collections/${VIP_EMAIL_LINK_COLLECTION}/records`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
body: JSON.stringify(recordBody),
|
||||
});
|
||||
if (!createRes.ok) {
|
||||
const err = await createRes.json().catch(() => ({}));
|
||||
return NextResponse.json({ ok: false, error: err?.message || "写入失败" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
console.log("[store-email-link] 成功 email=%s user_id=%s", email, userId);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error("[store-email-link] error:", e);
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: e instanceof Error ? e.message : "操作失败" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,46 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
|
||||
import {
|
||||
COOKIE_NAME,
|
||||
getCookieOptions,
|
||||
getHostFromRequest,
|
||||
} from "@/app/lib/auth-cookie";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const token = body?.token;
|
||||
const record = body?.record;
|
||||
const anonymousUserId =
|
||||
typeof body?.anonymousUserId === "string" ? body.anonymousUserId.trim() : "";
|
||||
|
||||
if (!token || !record?.id) {
|
||||
return NextResponse.json({ ok: false, error: "缺少 token 或 record" }, { status: 400 });
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "缺少 token 或 record" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const payload = JSON.stringify({
|
||||
const payload: Record<string, string> = {
|
||||
token,
|
||||
userId: record.id,
|
||||
email: record.email ?? "",
|
||||
});
|
||||
const encoded = Buffer.from(payload, "utf-8").toString("base64url");
|
||||
};
|
||||
|
||||
if (/^user\d+$/.test(anonymousUserId)) {
|
||||
payload.anonymousUserId = anonymousUserId;
|
||||
}
|
||||
|
||||
const encoded = Buffer.from(JSON.stringify(payload), "utf-8").toString(
|
||||
"base64url"
|
||||
);
|
||||
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
|
||||
res.cookies.set(
|
||||
COOKIE_NAME,
|
||||
encoded,
|
||||
getCookieOptions(false, getHostFromRequest(request)) as Record<
|
||||
string,
|
||||
string | number | boolean
|
||||
>
|
||||
);
|
||||
return res;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user