Files
anouma/collections/Customers.ts
T

141 lines
5.2 KiB
TypeScript

import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig } from "payload";
import { isAdmin, 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";
// Routes through the shared isAdmin check (role === "admin", not just
// collection === "users") so this stays correct if a non-admin role is ever
// added to Users — see the comment on isAdmin in access/index.ts.
const isSelfOrAdmin: typeof isAdmin = (args) => {
const user = args.req.user;
if (!user) return false;
if (user.collection === "users") return isAdmin(args);
if (user.collection === "customers") return { id: { equals: user.id } };
return false;
};
// Runs on every new customer account, and again whenever an existing
// customer changes their email address: issues a random, single-use,
// time-limited email-verification token and resets emailVerified to false.
// Only the token's hash is ever persisted (see emailVerificationTokenHash
// 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.
//
// The email-change case matters because `update` access on this collection
// is isSelfOrAdmin and the auto-added `email` field carries no field-level
// access of its own — without this, a customer could verify a throwaway
// address once and then repoint `email` at an address they don't own while
// keeping emailVerified: true (which gates booking-confirmation emails).
const issueVerificationToken: CollectionBeforeChangeHook = ({ data, originalDoc, operation, req }) => {
const emailChanged =
operation === "update" &&
typeof data.email === "string" &&
typeof originalDoc?.email === "string" &&
data.email !== originalDoc.email;
if (operation !== "create" && !emailChanged) 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, req }) => {
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: "Kunden",
},
admin: {
useAsTitle: "name",
defaultColumns: ["name", "email", "phone"],
group: "Buchungen",
description: "Konten der Website-Besucher (nicht die Admin-Zugänge unter „Benutzer“).",
},
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: isAdmin,
},
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.
],
};