137 lines
3.2 KiB
TypeScript
137 lines
3.2 KiB
TypeScript
import "server-only";
|
|
|
|
import { betterAuth } from "better-auth";
|
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
import { nextCookies } from "better-auth/next-js";
|
|
import { headers } from "next/headers";
|
|
|
|
import { getDb } from "@/db";
|
|
import {
|
|
accounts,
|
|
sessions,
|
|
users,
|
|
verifications,
|
|
} from "@/db/schema";
|
|
|
|
import {
|
|
isAllowedAdminRegistration,
|
|
isAuthorizedAdmin,
|
|
isConfiguredAdminEmail,
|
|
type SessionUserLike,
|
|
} from "./authorization";
|
|
|
|
function required(name: string): string {
|
|
const value = process.env[name];
|
|
if (!value) throw new Error(`${name} is required for authentication.`);
|
|
return value;
|
|
}
|
|
|
|
function createAuth() {
|
|
const adminEmail = required("ADMIN_EMAIL");
|
|
|
|
return betterAuth({
|
|
appName: "Buzz Sheet",
|
|
database: drizzleAdapter(getDb(), {
|
|
provider: "pg",
|
|
schema: {
|
|
user: users,
|
|
session: sessions,
|
|
account: accounts,
|
|
verification: verifications,
|
|
},
|
|
transaction: true,
|
|
}),
|
|
baseURL: required("BETTER_AUTH_URL"),
|
|
trustedOrigins: process.env.BETTER_AUTH_TRUSTED_ORIGINS
|
|
?.split(",")
|
|
.map((origin) => origin.trim())
|
|
.filter(Boolean),
|
|
secret: required("BETTER_AUTH_SECRET"),
|
|
emailAndPassword: {
|
|
enabled: true,
|
|
minPasswordLength: 8,
|
|
maxPasswordLength: 128,
|
|
},
|
|
user: {
|
|
validateUserInfo: async ({ user, source }) => {
|
|
if (
|
|
!isAllowedAdminRegistration(
|
|
user.email,
|
|
source.method,
|
|
adminEmail,
|
|
)
|
|
) {
|
|
return {
|
|
error: "ADMIN_REGISTRATION_FORBIDDEN",
|
|
errorDescription:
|
|
"Registration is limited to the configured administrator.",
|
|
};
|
|
}
|
|
},
|
|
},
|
|
databaseHooks: {
|
|
user: {
|
|
create: {
|
|
before: async (user) => {
|
|
if (!isConfiguredAdminEmail(user.email, adminEmail)) return false;
|
|
return { data: { emailVerified: true } };
|
|
},
|
|
},
|
|
},
|
|
},
|
|
plugins: [nextCookies()],
|
|
});
|
|
}
|
|
|
|
type AuthInstance = ReturnType<typeof createAuth>;
|
|
let authInstance: AuthInstance | undefined;
|
|
|
|
export function getAuth(): AuthInstance {
|
|
if (!authInstance) authInstance = createAuth();
|
|
return authInstance;
|
|
}
|
|
|
|
export interface AdminSession {
|
|
user: SessionUserLike;
|
|
session: { id: string };
|
|
}
|
|
|
|
export async function getAdminSession(): Promise<AdminSession | null> {
|
|
if (process.env.BUZZ_DEMO_MODE === "true") {
|
|
return {
|
|
user: {
|
|
id: "demo-admin",
|
|
email: "[email protected]",
|
|
emailVerified: true,
|
|
name: "Demo Admin",
|
|
},
|
|
session: { id: "demo-session" },
|
|
};
|
|
}
|
|
|
|
const session = await getAuth().api.getSession({ headers: await headers() });
|
|
if (
|
|
!session?.session ||
|
|
!isAuthorizedAdmin(session.user, process.env.ADMIN_EMAIL)
|
|
) {
|
|
return null;
|
|
}
|
|
return {
|
|
user: session.user,
|
|
session: { id: session.session.id },
|
|
};
|
|
}
|
|
|
|
export class AdminAuthorizationError extends Error {
|
|
constructor() {
|
|
super("Admin authorization required.");
|
|
this.name = "AdminAuthorizationError";
|
|
}
|
|
}
|
|
|
|
export async function requireAdmin(): Promise<AdminSession> {
|
|
const session = await getAdminSession();
|
|
if (!session) throw new AdminAuthorizationError();
|
|
return session;
|
|
}
|