45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import { getPocketBaseConfig } from "@/config/services.config";
|
|
|
|
let cachedToken: { token: string; expiresAt: number } | null = null;
|
|
const TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
|
|
/**
|
|
* PocketBase v0.23+ 使用 _superusers 集合替代旧 /api/admins 端点。
|
|
* 此函数依次尝试新旧两个端点,兼容所有版本。
|
|
*/
|
|
export async function getAdminToken(): Promise<string | null> {
|
|
if (cachedToken && Date.now() < cachedToken.expiresAt) {
|
|
return cachedToken.token;
|
|
}
|
|
|
|
const email = process.env.POCKETBASE_EMAIL;
|
|
const password = process.env.POCKETBASE_PASSWORD;
|
|
if (!email || !password) return null;
|
|
|
|
const pb = getPocketBaseConfig();
|
|
const base = pb.url.replace(/\/$/, "");
|
|
const body = JSON.stringify({ identity: email, password });
|
|
const headers = { "Content-Type": "application/json" };
|
|
|
|
const endpoints = [
|
|
`${base}/api/collections/_superusers/auth-with-password`,
|
|
`${base}/api/admins/auth-with-password`,
|
|
];
|
|
|
|
for (const url of endpoints) {
|
|
try {
|
|
const res = await fetch(url, { method: "POST", headers, body });
|
|
if (!res.ok) continue;
|
|
const data = await res.json();
|
|
const token = data?.token;
|
|
if (token) {
|
|
cachedToken = { token, expiresAt: Date.now() + TOKEN_TTL_MS };
|
|
return token;
|
|
}
|
|
} catch {
|
|
continue;
|
|
}
|
|
}
|
|
return null;
|
|
}
|