/** * 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) }; } module.exports = { findAccountByContact, hasValidEmail };