41 lines
1.2 KiB
TypeScript
41 lines
1.2 KiB
TypeScript
import { getPocketBaseConfig } from "@/config/services.config";
|
|
|
|
let cachedToken: { token: string; expiresAt: number } | null = null;
|
|
const TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
|
|
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;
|
|
}
|