/** * Finding an existing account from an email and/or phone number. * * Email and phone are looked up separately rather than with one OR query, so an email * belonging to one account and a phone belonging to another can never be silently * collapsed into whichever matches first — that would let a registration hijack or * corrupt someone else's account. Phones are tried in both 27xxx and 0xxx forms. */ const prisma = require('../config/db'); function hasValidEmail(email) { return !!(email && typeof email === 'string' && email.includes('@')); } /** * @returns {Promise<{ phone: string, emailUser: object|null, phoneUser: object|null, * conflict: boolean, user: object|null }>} * `user` is the single matched account (null when none, or when email and phone point * at two different accounts — `conflict` is then true). */ async function findAccountByContact({ email, phone: rawPhone }, db = prisma) { const { normalizeZAPhone } = require('./whatsapp'); const phone = normalizeZAPhone(rawPhone) || String(rawPhone || '').replace(/\D/g, ''); const phoneAlt = phone && phone.startsWith('27') ? '0' + phone.slice(2) : (phone && phone.length === 9 ? '27' + phone : null); const [emailUser, phoneUser] = await Promise.all([ hasValidEmail(email) ? db.user.findUnique({ where: { email: String(email).trim() } }) : null, phone ? db.user.findFirst({ where: { OR: [{ phoneNumber: phone }, ...(phoneAlt ? [{ phoneNumber: phoneAlt }] : [])] } }) : null, ]); const conflict = !!(emailUser && phoneUser && emailUser.id !== phoneUser.id); return { phone, emailUser, phoneUser, conflict, user: conflict ? null : (emailUser || phoneUser || null) }; } /** * The account for these contact details, or a new inactive one (same as guest * registration: a placeholder email for phone-only people, a random password, and an * activation link sent by the caller when `created` is true). */ async function findOrCreateAccount({ name, email, phone }, db = prisma) { const match = await findAccountByContact({ email, phone }, db); if (match.conflict) { const err = new Error('That email address and phone number belong to two different accounts. Use just one of them.'); err.statusCode = 400; throw err; } if (match.user) return { user: match.user, created: false }; const { v4: uuidv4 } = require('uuid'); const { hashPassword } = require('../config/auth'); const validEmail = hasValidEmail(email); const user = await db.user.create({ data: { id: uuidv4(), name, email: validEmail ? String(email).trim() : `guest+${uuidv4().slice(0, 8)}@guest.local`, password: await hashPassword(uuidv4()), phoneNumber: match.phone || null, isActive: false, notificationPreference: validEmail && match.phone ? 'both' : validEmail ? 'email' : 'whatsapp', updatedAt: new Date(), }, }); return { user, created: true }; } module.exports = { findAccountByContact, findOrCreateAccount, hasValidEmail };