Files
helios-evcs/apps/csms/src/lib/auth.ts

53 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { useDrizzle } from "./db.js";
import * as schema from "@/db/schema.ts";
import { admin, bearer, username } from "better-auth/plugins";
import { passkey } from "@better-auth/passkey";
const webOrigin = process.env.WEB_ORIGIN ?? "http://localhost:3000";
const rpID = new URL(webOrigin).hostname;
// 从 WEB_ORIGIN 的主机名推导父域(如 csms.uniiem.com → uniiem.com
// 用于跨子域共享 session cookie本地开发时返回 undefined 不启用。
function getParentDomain(hostname: string): string | undefined {
if (hostname === "localhost" || /^\d/.test(hostname)) return undefined;
const parts = hostname.split(".");
return parts.length >= 3 ? parts.slice(1).join(".") : undefined;
}
const cookieDomain = process.env.COOKIE_DOMAIN ?? getParentDomain(rpID);
export const auth = betterAuth({
database: drizzleAdapter(useDrizzle(), {
provider: "pg",
schema: {
...schema,
},
}),
trustedOrigins: [webOrigin],
appName: "Helios EVCS",
user: {
additionalFields: {},
},
emailAndPassword: {
enabled: true,
},
plugins: [
admin(),
username(),
bearer(),
passkey({
rpID,
rpName: "Helios EVCS",
origin: webOrigin,
}),
],
advanced: {
cookiePrefix: "helios_auth",
crossSubdomainCookies: cookieDomain
? { enabled: true, domain: cookieDomain }
: { enabled: false },
},
});