import { getCMS } from "@/lib/payload/getPayload"; import { hashVerificationToken } from "@/lib/auth/verification"; const TOKEN_SHAPE = /^[0-9a-f]{64}$/i; /** * Verifies a token from a /auth/verify-email/[token] link: looks it up by * hash (the plaintext is never stored), checks it hasn't expired, then * marks the account verified and immediately clears the hash + expiry so * the same link can never be used a second time. */ export async function verifyEmailToken(token: string): Promise { if (!TOKEN_SHAPE.test(token)) return false; const payload = await getCMS(); const hash = hashVerificationToken(token); const { docs } = await payload.find({ collection: "customers", where: { emailVerificationTokenHash: { equals: hash } }, limit: 1, }); const customer = docs[0]; if (!customer || !customer.emailVerificationExpires) return false; if (new Date(customer.emailVerificationExpires).getTime() < Date.now()) return false; await payload.update({ collection: "customers", id: customer.id, data: { emailVerified: true, emailVerificationTokenHash: null, emailVerificationExpires: null, }, }); return true; }