import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig } from "payload"; import { isAdminFieldLevel } from "@/access"; import { EMAIL_VERIFICATION_TTL_MS, generateVerificationToken, hashVerificationToken, verificationExpiryISO } from "@/lib/auth/verification"; import { verificationEmail } from "@/lib/email/authTemplates"; import { sendEmail } from "@/lib/email/sendBookingEmails"; const isSelfOrAdmin = ({ req }: { req: { user?: { collection?: string; id?: unknown } | null } }) => { const user = req.user; if (!user) return false; if (user.collection === "users") return true; if (user.collection === "customers") return { id: { equals: user.id } }; return false; }; // Runs on every new customer account: issues a random, single-use, // time-limited email-verification token. Only its hash is ever persisted // (see the emailVerificationTokenHash field below) — the plaintext exists // only in req.context for the afterChange hook below to email out, and is // never written to the database or logged. const issueVerificationToken: CollectionBeforeChangeHook = ({ data, operation, req }) => { if (operation !== "create") return data; const token = generateVerificationToken(); data.emailVerified = false; data.emailVerificationTokenHash = hashVerificationToken(token); data.emailVerificationExpires = verificationExpiryISO(); req.context.pendingVerificationToken = token; return data; }; const sendVerificationEmail: CollectionAfterChangeHook = async ({ doc, operation, req }) => { if (operation !== "create") return doc; const token = req.context.pendingVerificationToken; if (typeof token !== "string") return doc; try { const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:3000"; await sendEmail( doc.email, verificationEmail({ name: doc.name, verifyUrl: `${serverUrl}/auth/verify-email/${token}`, expiresHours: Math.round(EMAIL_VERIFICATION_TTL_MS / (60 * 60 * 1000)), }), ); } catch (err) { req.payload.logger.error({ err, msg: "customers sendVerificationEmail failed" }); } return doc; }; export const Customers: CollectionConfig = { slug: "customers", labels: { singular: "Kundin/Kunde", plural: "Kund:innen", }, admin: { useAsTitle: "name", defaultColumns: ["name", "email", "phone"], group: "Buchungen", description: "Konten der Website-Besucher:innen (nicht die Admin-Zugänge unter „Benutzer:innen“).", }, auth: { maxLoginAttempts: 8, lockTime: 10 * 60 * 1000, }, access: { // Anyone can create their own account (registration); reading/updating // is restricted to the account owner or an admin. create: () => true, read: isSelfOrAdmin, update: isSelfOrAdmin, delete: ({ req }) => req.user?.collection === "users", }, hooks: { beforeChange: [issueVerificationToken], afterChange: [sendVerificationEmail], }, fields: [ { name: "name", type: "text", label: "Name", required: true, }, { name: "phone", type: "text", label: "Telefonnummer", required: false, admin: { description: "Optional — für eine spätere Nutzung vorbereitet, aktuell nicht verpflichtend.", }, }, { name: "emailVerified", type: "checkbox", label: "E-Mail bestätigt", defaultValue: false, // "create" AND "update" must both be locked down — otherwise a // customer could simply include emailVerified: true in their own // registration or profile request and skip verification entirely. access: { create: isAdminFieldLevel, update: isAdminFieldLevel }, admin: { position: "sidebar", description: "Wird automatisch gesetzt, sobald der Bestätigungslink aus der E-Mail angeklickt wird. Kann hier bei Bedarf manuell gesetzt werden.", }, }, { name: "emailVerificationTokenHash", type: "text", // Never exposed or settable via any API — only the two hooks above // (running through the trusted Local API) ever touch this field. access: { create: () => false, read: () => false, update: () => false }, admin: { hidden: true }, index: true, }, { name: "emailVerificationExpires", type: "date", access: { create: () => false, read: () => false, update: () => false }, admin: { hidden: true }, }, // "email" and "password" are added automatically by the auth config. ], };