Files
Epicure/apps/web/lib/auth/server.ts
T
Arnaud e0e1ac49d9 feat: signup toggle, invite links, admin-created users
- New invites table: token-gated signup, optional email lock,
  role/tier override, single-use, expiry.
- SIGNUPS_DISABLED site setting toggle at /admin/settings.
- databaseHooks.user.create gate in auth/server.ts blocks new account
  creation (email + Google OAuth) when disabled unless a valid invite
  cookie is present; applies invite role/tier and marks it consumed.
- /admin/invites: create/list/revoke shareable invite links.
- /admin/users: "Create user" dialog — admin sets email/role/tier,
  account is pre-verified, user gets a set-password email (admin
  never sees a password).
- Signup page reads ?invite=, validates via public
  /api/v1/invites/[token], locks the form when signups are closed
  and no valid invite is present.
- proxy.ts: allowlist /api/v1/invites/ for anonymous invite checks.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-03 21:36:40 +02:00

167 lines
4.8 KiB
TypeScript

import { betterAuth } from "better-auth";
import { genericOAuth } from "better-auth/plugins";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db, users, sessions, accounts, verifications, eq, count } from "@epicure/db";
import { sendEmail, verifyEmailHtml, resetPasswordHtml, welcomeHtml } from "@/lib/email";
import { isSignupsDisabled } from "@/lib/site-settings";
import { findValidInvite, consumeInvite, INVITE_COOKIE } from "@/lib/invites";
export const auth = betterAuth({
trustedOrigins: [process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"],
database: drizzleAdapter(db, {
provider: "pg",
schema: { user: users, session: sessions, account: accounts, verification: verifications },
}),
emailAndPassword: {
enabled: true,
requireEmailVerification: true,
sendResetPassword: async ({ user, url }) => {
await sendEmail({
to: user.email,
subject: "Reset your Epicure password",
html: resetPasswordHtml(url),
});
},
},
emailVerification: {
sendOnSignUp: true,
autoSignInAfterVerification: true,
sendVerificationEmail: async ({ user, url }) => {
await sendEmail({
to: user.email,
subject: "Verify your Epicure email",
html: verifyEmailHtml(url),
});
},
},
socialProviders: {
google: {
clientId: process.env["GOOGLE_CLIENT_ID"] ?? "",
clientSecret: process.env["GOOGLE_CLIENT_SECRET"] ?? "",
},
...(process.env["GITHUB_CLIENT_ID"] && {
github: {
clientId: process.env["GITHUB_CLIENT_ID"],
clientSecret: process.env["GITHUB_CLIENT_SECRET"] ?? "",
},
}),
...(process.env["DISCORD_CLIENT_ID"] && {
discord: {
clientId: process.env["DISCORD_CLIENT_ID"],
clientSecret: process.env["DISCORD_CLIENT_SECRET"] ?? "",
},
}),
},
plugins: [
...(process.env["AUTHENTIK_CLIENT_ID"] && process.env["AUTHENTIK_BASE_URL"] ? [
genericOAuth({
config: [
{
providerId: "authentik",
clientId: process.env["AUTHENTIK_CLIENT_ID"],
clientSecret: process.env["AUTHENTIK_CLIENT_SECRET"] ?? "",
// Authentik OIDC discovery URL: https://<your-authentik-domain>/application/o/<slug>/
discoveryUrl: `${process.env["AUTHENTIK_BASE_URL"]}/.well-known/openid-configuration`,
scopes: ["openid", "email", "profile"],
},
],
}),
] : []),
],
session: {
cookieCache: {
enabled: true,
maxAge: 60 * 5,
},
},
databaseHooks: {
user: {
create: {
before: async (user, context) => {
if (!(await isSignupsDisabled())) return;
const token = context?.getCookie(INVITE_COOKIE);
const invite = token ? await findValidInvite(token, user.email) : null;
if (!invite) return false;
return { data: { ...user, role: invite.role, tier: invite.tier } };
},
after: async (user, context) => {
// First registered user becomes admin
const result = await db.select({ total: count() }).from(users);
if ((result[0]?.total ?? 0) === 1) {
await db.update(users).set({ role: "admin" }).where(eq(users.id, user.id));
}
// Consume the invite that gated this signup, if any (regardless of
// whether signups have since been re-enabled/disabled).
const token = context?.getCookie(INVITE_COOKIE);
const invite = token ? await findValidInvite(token, user.email) : null;
if (invite) await consumeInvite(invite.id, user.id);
// Welcome email (fire and forget)
sendEmail({
to: user.email,
subject: "Welcome to Epicure",
html: welcomeHtml(user.name),
}).catch(() => {});
},
},
},
},
user: {
fields: {
image: "avatarUrl",
},
additionalFields: {
role: {
type: "string",
defaultValue: "user",
input: false,
},
tier: {
type: "string",
defaultValue: "free",
input: false,
},
username: {
type: "string",
required: false,
},
bio: {
type: "string",
required: false,
},
unitPref: {
type: "string",
defaultValue: "metric",
},
locale: {
type: "string",
defaultValue: "en",
},
},
changeEmail: {
enabled: true,
sendChangeEmailVerification: async ({ newEmail, url }: { newEmail: string; url: string }) => {
await sendEmail({
to: newEmail,
subject: "Verify your new Epicure email",
html: verifyEmailHtml(url),
});
},
},
},
});
export type Session = typeof auth.$Infer.Session;
export type User = typeof auth.$Infer.Session.user;