Files
Epicure/apps/web/lib/auth/server.ts
T
Arnaud d7e0d7eada feat: profile pictures — Gravatar fallback + custom upload
New users get a Gravatar-backed avatar automatically (computed from email
at signup); users can upload a custom photo instead via Settings, or
revert to the Gravatar/initials fallback. avatarUrl stays the single
resolved value (custom photo, OAuth photo, or precomputed Gravatar URL)
so every existing avatar-rendering spot across the app needs zero changes.

- users.hasCustomAvatar tracks whether avatarUrl is a real upload vs a
  computed Gravatar fallback, so "remove photo" knows what to revert to.
- New /api/v1/upload/avatar-presign route (session-scoped, generic —
  the existing recipe-photo presign route required a recipeId).
- CSP img-src needed www.gravatar.com added, or every browser blocks
  the fallback avatar outright.
- Settings page now reads avatarUrl from a fresh DB query instead of
  Better Auth's session object — the session cookie cache (5 min TTL)
  was serving a stale image right after upload, showing the initials
  fallback until the cache happened to expire.

Verified locally: signup auto-sets a Gravatar URL, upload persists
across reload, remove correctly reverts to Gravatar/initials.
2026-07-12 16:10:54 +02:00

175 lines
5.2 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";
import { gravatarUrl } from "@/lib/gravatar";
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));
}
// Only email/password signups land here without an avatar already
// set (OAuth providers set `image` — mapped to avatarUrl — before
// this hook runs) — give them a Gravatar-backed default.
if (!user.image) {
await db.update(users).set({ avatarUrl: gravatarUrl(user.email) }).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;