CTF SIGNUP / REGISTRATION → EMAIL FLOW ======================================= Purpose ------- This handoff describes the current backend path for a public registration, from POST /v1/registrations/register through persistence, Registration QR generation, QR email delivery, email_logs persistence, and the HTTP response. The code excerpts below are taken from the current repository. They include only code used by this signup path. The later badge-issuance path is not part of this flow. Environment configuration is shown only as process.env references. No .env values are included. 1. HIGH-LEVEL FLOW ================== The application mounts the registration router at /v1/registrations: Source: app.js app.use("/v1/registrations", registrationRoutes); The current registration sequence is: POST /v1/registrations/register ↓ registration route + public rate limiter ↓ register controller ↓ createRegistrationEntry(req.body) ↓ read active registration_fields and validate/normalize responses ↓ insert registrants row ↓ insert registration_field_answers rows ↓ create registration_qr row ↓ generate a QR PNG from registration_qr.hashedId ↓ send registration email through util/mailer.js / nodemailer ↓ insert email_logs row with status sent or failed ↓ return HTTP 201 registration response Table-level summary of the main path: POST /v1/registrations/register → registration_fields (read active form definitions) → registrants (main registration row) → registration_field_answers (dynamic answer rows) → registration_qr (one emailed registration QR identity) → SMTP email with the QR attachment → email_logs (delivery attempt result) → HTTP response There is no Sequelize transaction in the current createRegistrationEntry() implementation. The database operations run sequentially. SMTP delivery is attempted only after the registrant, answer rows, and registration_qr row have been written. 2. REGISTER ROUTE ================= Source: routes/registration.routes.js The current public-registration limiter and route definition are: const registrationLimiter = rateLimit({ windowMs: 60 * 1000, max: 10 }); // STEP 1 — public registration router.post("/register", registrationLimiter, register); Combined with the app.js mount shown above, this is: POST /v1/registrations/register The route does not use staff authentication. It runs the public registrationLimiter (10 requests per 60 seconds) and then calls the imported register controller. 3. REGISTER CONTROLLER ====================== Source: controllers/registration.controller.js Function: exports.register exports.register = async (req, res, next) => { try { const { guid, ticketId, source, emailDelivered, registrationQr } = await registrationHelpers.createRegistrationEntry(req.body); const data = { guid, ticketId, source, emailDelivered }; // Online attendees need the image immediately so the frontend can show // it after registration. This is the same QR payload used by the email. if (source === "online") data.registrationQr = registrationQr; return res.status(201).json({ success: true, message: emailDelivered ? "Registration submitted successfully. Please check your email for your QR code." : "Registration submitted, but we could not email your QR code. Please contact support.", data, }); } catch (err) { next(err); } }; What this controller does: * It passes the complete request body to createRegistrationEntry(req.body). * The helper reads responses and source from that body. The active form definitions determine which response keys are recognized and validated. * The helper returns guid, ticketId, source, emailDelivered, and the QR result. * The controller always exposes guid, ticketId, source, and emailDelivered in data. It exposes data.registrationQr only when source is exactly "online". * The online registrationQr object contains qrImageBase64 generated by the same QR send helper that creates the email attachment. * SMTP failure does not make the registration fail: the helper returns emailDelivered: false after writing a failed email log, so the controller returns HTTP 201 with the failure message. An unexpected error that escapes the helper is passed to next(err). 4. REGISTRATION CREATION / DATABASE INSERTS =========================================== Source: controllers/registration-helpers.js Relevant helper: createRegistrationEntry The helper imports the models and utilities used by this path: const QRCode = require("qrcode"); const path = require("path"); const fs = require("fs"); const Registrant = require("../models/Registrant"); const RegistrationField = require("../models/RegistrationField"); const RegistrationFieldAnswer = require("../models/RegistrationFieldAnswer"); const RegistrationQR = require("../models/RegistrationQR"); const EmailLog = require("../models/EmailLog"); const sendMail = require("../util/mailer"); const registrationQrEmailTemplate = require("../templates/registration-qr-email"); const { hashGuid, generateUniqueTicketId } = require("../util/idGenerators"); const normalizeEmail = require("../util/normalizeEmail"); Duplicate normalized email addresses are intentionally allowed. The helper does not perform an active-registration duplicate lookup and does not convert database uniqueness errors into email-specific HTTP 409 responses. The normalized value is retained for deterministic resend lookup only; unrelated database errors still propagate normally. The JSON parser used for dynamic field options and validation is: const parseMaybeJson = (value) => { if (typeof value === "string") { try { return JSON.parse(value); } catch (e) { return value; } } return value; }; Exact current createRegistrationEntry() implementation: const createRegistrationEntry = async ( fields, { sendRegistrationQr = sendRegistrationQrEmail, sendEmail = true } = {}, ) => { const { responses = {}, source } = fields; const resolvedSource = source && typeof source === "string" ? source : "direct"; const formFields = await RegistrationField.findAll({ where: { active: 1 }, order: [ ["displayOrder", "ASC"], ["id", "ASC"], ], }); const cleanedResponses = {}; const roleValues = { fullName: null, firstName: null, lastName: null, email: null, mobileNumber: null, company: null, }; const readableAnswers = []; for (const field of formFields) { let raw = responses[field.fieldKey]; if (field.fieldRole === "email" && raw !== undefined && raw !== null) { raw = normalizeEmail(raw); } const fieldOptions = parseMaybeJson(field.options); const validation = parseMaybeJson(field.validation) || {}; const isEmpty = raw === undefined || raw === null || raw === "" || (Array.isArray(raw) && raw.length === 0); if (validation.required && isEmpty) { const err = new Error(`"${field.label}" is required.`); err.statusCode = 400; throw err; } if (isEmpty) continue; switch (field.fieldType) { case "radio": { const allowed = (fieldOptions || []).map((o) => o.value); if (!allowed.includes(raw)) { const err = new Error(`"${field.label}" has an invalid value.`); err.statusCode = 400; throw err; } break; } case "checkbox": { const allowed = (fieldOptions || []).map((o) => o.value); const values = Array.isArray(raw) ? raw : [raw]; const invalid = values.some((v) => !allowed.includes(v)); if (invalid) { const err = new Error(`"${field.label}" has an invalid value.`); err.statusCode = 400; throw err; } break; } default: { if (validation.minLength && String(raw).length < validation.minLength) { const err = new Error( `"${field.label}" must be at least ${validation.minLength} characters.`, ); err.statusCode = 400; throw err; } if (validation.maxLength && String(raw).length > validation.maxLength) { const err = new Error( `"${field.label}" must be at most ${validation.maxLength} characters.`, ); err.statusCode = 400; throw err; } if ( validation.pattern && !new RegExp(validation.pattern).test(String(raw)) ) { const err = new Error(`"${field.label}" is not in a valid format.`); err.statusCode = 400; throw err; } } } cleanedResponses[field.fieldKey] = raw; if (field.fieldRole && field.fieldRole !== "none") { roleValues[field.fieldRole] = raw; } let readableValue; if (field.fieldType === "radio") { const match = (fieldOptions || []).find((o) => o.value === raw); readableValue = match ? match.label : raw; } else if (field.fieldType === "checkbox") { const values = Array.isArray(raw) ? raw : [raw]; readableValue = values .map((v) => { const match = (fieldOptions || []).find((o) => o.value === v); return match ? match.label : v; }) .join(", "); } else { readableValue = String(raw); } readableAnswers.push({ registrationFieldId: field.id, fieldLabel: field.label, fieldType: field.fieldType, answerValue: readableValue, }); } const fullName = roleValues.fullName || [roleValues.firstName, roleValues.lastName] .filter(Boolean) .join(" ") .trim() || null; const email = normalizeEmail(roleValues.email); const mobileNumber = roleValues.mobileNumber; const company = roleValues.company; if (!email) { const err = new Error( "The registration form has no field mapped to the 'fullName' role (or 'firstName'/'lastName') — cannot generate the QR code.", ); err.statusCode = 422; throw err; } if (!fullName) { const err = new Error( "The registration form has no field mapped to the 'fullName' role — cannot generate the QR code.", ); err.statusCode = 422; throw err; } // Duplicate normalized email addresses are allowed. Position and // purpose_of_visit remain dynamic-only response/answer values. const entity = await Registrant.create({ responses: cleanedResponses, fullName, email, normalizedEmail: email, mobileNumber, company, source: resolvedSource, active: 1, }); if (readableAnswers.length > 0) { await RegistrationFieldAnswer.bulkCreate( readableAnswers.map((a) => ({ ...a, registrantId: entity.id })), ); } const hashedId = hashGuid(entity.guid); const year = new Date().getFullYear(); const ticketId = await generateUniqueTicketId(year); const registrationQr = await RegistrationQR.create({ registrantGuid: entity.guid, hashedId, ticketId, }); // Shared send path — uses the SAME QR identity/hashedId used by every // later resend. Registration persistence and email delivery are separate // outcomes: emailDelivered only reports the mail. const deliveryResult = sendEmail ? await sendRegistrationQr({ registrant: entity, registrationQr, }) : { emailDelivered: false, registrationQr: null }; return { guid: entity.guid, ticketId, source: resolvedSource, emailDelivered: deliveryResult.emailDelivered, registrationQr: deliveryResult.registrationQr || null, }; }; Registration-processing details: 1. fields is the request body. The current function reads responses (default {}) and source. If source is not a string, source becomes "direct". 2. Only active registration_fields rows are loaded, ordered by displayOrder and then id. 3. Each submitted value is looked up by field.fieldKey. Email-role values are trimmed/lower-cased by normalizeEmail before validation and persistence. 4. Required fields, radio/checkbox options, minLength, maxLength, and pattern validation are enforced from the active field definition. 5. cleanedResponses contains the accepted raw values and is stored in the registrants.responses JSON column. roleValues extracts fullName or firstName/lastName, email, mobileNumber, and company for direct columns. 6. readableAnswers contains one denormalized answer object for each non-empty submitted dynamic field. Radio and checkbox values are converted to labels where the active field options provide a matching label. 7. Duplicate normalized email addresses are allowed. The normalized value is retained for lookup/resend behavior, but registration performs no active duplicate lookup and does not convert unrelated database errors into an email-specific 409 response. 8. Registrant.create() runs before the answer bulk insert, then the RegistrationQR row is created, then email delivery is attempted. Code operation → database table ------------------------------- RegistrationField.findAll({ where: { active: 1 }, ... }) → registration_fields (read active form definitions) Registrant.create({ ... }) → registrants (main registrant insert) RegistrationFieldAnswer.bulkCreate( readableAnswers.map((a) => ({ ...a, registrantId: entity.id })) ) → registration_field_answers (dynamic answer inserts) RegistrationQR.findOne({ where: { ticketId } }) → registration_qr (ticket collision check inside ticket generation) RegistrationQR.create({ registrantGuid, hashedId, ticketId }) → registration_qr (one Registration QR identity) EmailLog.create({ ... }) → email_logs (sent/failed delivery attempt; see Section 7) Relevant current model definitions ---------------------------------- Source: util/normalizeEmail.js "use strict"; // One canonical representation for normalized lookup/resend behavior. // This helper is shared by registration, resend lookup, and the Registrant // model hook so all paths apply the same trim + case-fold behavior without // making normalized email values unique. const normalizeEmail = (value) => String(value || "").trim().toLowerCase(); module.exports = normalizeEmail; Source: models/RegistrationField.js const Sequelize = require("sequelize"); const connection = require("../connection/database"); const RegistrationField = connection.define( "registration_fields", { id: { autoIncrement: true, primaryKey: true, type: Sequelize.BIGINT, allowNull: false, }, fieldKey: { type: Sequelize.STRING(100), allowNull: false, unique: true }, label: { type: Sequelize.TEXT, allowNull: false }, fieldType: { type: Sequelize.ENUM("text", "radio", "checkbox"), allowNull: false, }, fieldRole: { type: Sequelize.ENUM( "none", "fullName", "firstName", "lastName", "email", "mobileNumber", "company", "position", ), allowNull: false, defaultValue: "none", }, options: { type: Sequelize.JSON, allowNull: true, get() { const raw = this.getDataValue("options"); if (typeof raw === "string") { try { return JSON.parse(raw); } catch (e) { return raw; } } return raw; }, }, validation: { type: Sequelize.JSON, allowNull: true, get() { const raw = this.getDataValue("validation"); if (typeof raw === "string") { try { return JSON.parse(raw); } catch (e) { return raw; } } return raw; }, }, placeholder: { type: Sequelize.STRING(255), allowNull: true }, helpText: { type: Sequelize.STRING(255), allowNull: true }, displayOrder: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0 }, active: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true }, }, { tableName: "registration_fields", timestamps: true }, ); module.exports = RegistrationField; Source: models/Registrant.js const Sequelize = require("sequelize"); const connection = require("../connection/database"); const normalizeEmail = require("../util/normalizeEmail"); const Registrant = connection.define( "registrants", { id: { autoIncrement: true, primaryKey: true, type: Sequelize.BIGINT, allowNull: false, }, guid: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, allowNull: false, unique: true, }, responses: { type: Sequelize.JSON, allowNull: true, get() { const raw = this.getDataValue("responses"); if (typeof raw === "string") { try { return JSON.parse(raw); } catch (e) { return raw; } } return raw; }, }, fullName: { type: Sequelize.STRING(255), allowNull: true }, email: { type: Sequelize.STRING(255), allowNull: true }, normalizedEmail: { type: Sequelize.STRING(255), allowNull: true, }, mobileNumber: { type: Sequelize.STRING(255), allowNull: true }, company: { type: Sequelize.STRING(255), allowNull: true }, source: { type: Sequelize.STRING(50), allowNull: false, defaultValue: "direct" }, active: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 }, }, { tableName: "registrants", timestamps: true, hooks: { beforeValidate(registrant) { const normalized = normalizeEmail(registrant.email); if (normalized) registrant.email = normalized; registrant.normalizedEmail = registrant.active === 1 || registrant.active === true || registrant.active === "1" ? normalized || null : null; }, }, }, ); module.exports = Registrant; Source: models/RegistrationFieldAnswer.js const Sequelize = require("sequelize"); const connection = require("../connection/database"); const RegistrationFieldAnswer = connection.define( "registration_field_answers", { id: { autoIncrement: true, primaryKey: true, type: Sequelize.BIGINT, allowNull: false, }, registrantId: { type: Sequelize.BIGINT, allowNull: false }, registrationFieldId: { type: Sequelize.BIGINT, allowNull: true }, fieldLabel: { type: Sequelize.TEXT, allowNull: false }, fieldType: { type: Sequelize.STRING(20), allowNull: false }, answerValue: { type: Sequelize.TEXT, allowNull: true }, }, { tableName: "registration_field_answers", timestamps: true }, ); module.exports = RegistrationFieldAnswer; Source: models/RegistrationQR.js const Sequelize = require("sequelize"); const connection = require("../connection/database"); const RegistrationQR = connection.define( "registration_qr", { id: { autoIncrement: true, primaryKey: true, type: Sequelize.BIGINT, allowNull: false }, registrantGuid: { type: Sequelize.UUID, allowNull: false, unique: true }, hashedId: { type: Sequelize.STRING(255), allowNull: false, unique: true }, ticketId: { type: Sequelize.STRING(30), allowNull: true, unique: true }, printedAt: { type: Sequelize.DATE, allowNull: true }, printed_by: { type: Sequelize.BIGINT, allowNull: true }, }, { tableName: "registration_qr", timestamps: true }, ); module.exports = RegistrationQR; Source: models/EmailLog.js const Sequelize = require("sequelize"); const connection = require("../connection/database"); const EmailLog = connection.define( "email_logs", { id: { autoIncrement: true, primaryKey: true, type: Sequelize.BIGINT, allowNull: false }, registrantGuid: { type: Sequelize.UUID, allowNull: true }, emailType: { type: Sequelize.ENUM("qr_code"), allowNull: false, defaultValue: "qr_code", }, recipientName: { type: Sequelize.STRING(255), allowNull: true }, recipientEmail: { type: Sequelize.STRING(255), allowNull: true }, subject: { type: Sequelize.STRING(255), allowNull: true }, ticketId: { type: Sequelize.STRING(100), allowNull: true }, qrCodeImage: { type: Sequelize.TEXT("long"), allowNull: true, }, status: { type: Sequelize.ENUM("sent", "failed"), allowNull: false, defaultValue: "sent", }, errorMessage: { type: Sequelize.TEXT, allowNull: true }, sentAt: { type: Sequelize.DATE, allowNull: true }, }, { tableName: "email_logs", timestamps: true }, ); module.exports = EmailLog; 5. QR GENERATION ================= Source: util/idGenerators.js Functions: hashGuid and generateUniqueTicketId The Registration QR identity is derived from the registrant GUID and is not the raw GUID. The ticket ID is generated before the registration_qr insert and is checked against existing registration_qr.ticketId values. const crypto = require("crypto"); const RegistrationQR = require("../models/RegistrationQR"); const hashGuid = (guid) => crypto.createHash("sha256").update(guid).digest("hex"); const generateUniqueTicketId = async (year) => { let ticketId, exists; do { const rand = String(Math.floor(100000 + Math.random() * 900000)); ticketId = `CTF-${year}-${rand}`; exists = await RegistrationQR.findOne({ where: { ticketId } }); } while (exists); return ticketId; }; Source: controllers/registration-helpers.js Function: sendRegistrationQrEmail — QR conversion portion The helper reads hashedId from the already-created registration_qr row: const { hashedId, ticketId } = registrationQr; const qrBuffer = await QRCode.toBuffer(hashedId, { width: 360, margin: 1 }); const qrCodeImage = qrBuffer.toString("base64"); The same generated QR data is then used in three ways: * qrBuffer becomes the inline qr.png email attachment. * qrCodeImage is stored in email_logs.qrCodeImage by logAndSendMail(). * qrCodeImage is returned as registrationQr.qrImageBase64 and is surfaced by the controller for source === "online". The email HTML references the attachment by CID registration-qr rather than embedding a second QR or generating a second identity. Therefore the frontend response and email both correspond to the same registration_qr.hashedId. The hashed QR identity is generated before RegistrationQR.create(), while the PNG image is generated afterward by sendRegistrationQrEmail() and before the SMTP call. If SMTP fails, the QR image can still be returned to the online frontend because the shared helper returns the generated image result. 6. EMAIL SENDING ================ Sources: controllers/registration-helpers.js util/mailer.js templates/registration-qr-email.js 6.1 Registration QR email helper -------------------------------- Source: controllers/registration-helpers.js Function: sendRegistrationQrEmail const sendRegistrationQrEmail = async ({ registrant, registrationQr, deliverMail = logAndSendMail, }) => { const fullName = registrant.fullName; const email = registrant.email; const { hashedId, ticketId } = registrationQr; const qrBuffer = await QRCode.toBuffer(hashedId, { width: 360, margin: 1 }); const qrCodeImage = qrBuffer.toString("base64"); const headerAttachment = getEventHeaderAttachment(); const template = registrationQrEmailTemplate( fullName, process.env.EVENT_NAME || "Coconut Trade Fair", ticketId, fmtDate(process.env.EVENT_START_DATE), fmtDate(process.env.EVENT_END_DATE), process.env.EVENT_LOCATION || "", `Please keep this email — you'll need the QR code to have your badge printed at the venue.`, !!headerAttachment, ); const attachments = []; if (headerAttachment) attachments.push(headerAttachment); attachments.push({ filename: "qr.png", content: qrBuffer, cid: "registration-qr", contentType: "image/png", contentDisposition: "inline", }); const emailDelivered = await deliverMail({ registrantGuid: registrant.guid, recipientName: fullName, recipientEmail: email, subject: "Your Coconut Trade Fair Registration QR Code", ticketId, qrCodeImage, sendArgs: [ template, "Your Coconut Trade Fair Registration QR Code", email, "", attachments, ], }); return { emailDelivered, // This is the exact image generated for the email attachment. Returning // it lets online registration surface the same QR without creating a // second RegistrationQR row or generating another identity. registrationQr: { qrImageBase64: qrCodeImage }, }; }; The helper is called by createRegistrationEntry() with the entity returned by Registrant.create() and the RegistrationQR returned by RegistrationQR.create(). Production uses the default deliverMail value, logAndSendMail. The optional deliverMail argument is only an injection seam used by tests. 6.2 Supporting event-header and date helpers --------------------------------------------- Source: controllers/registration-helpers.js const getEventHeaderAttachment = () => { const headerPath = path.join(__dirname, "../public/event-header.png"); if (!fs.existsSync(headerPath)) return null; return { filename: "event-header.png", path: headerPath, cid: "eventheader", contentType: "image/png", contentDisposition: "inline", }; }; const fmtDate = (d) => d ? new Date(d).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric", }) : ""; 6.3 SMTP mailer --------------- Source: util/mailer.js Function: module.exports The current mailer reads configuration from environment variables only. The actual environment values are intentionally not part of this handoff. const nodemailer = require("nodemailer"); module.exports = async (template, title, email, cc = "", attachments = []) => { return new Promise((resolve, reject) => { const transporter = nodemailer.createTransport({ host: process.env.MAIL_HOST, port: Number(process.env.MAIL_PORT || 465), secure: String(process.env.MAIL_SECURE || "true") === "true", auth: { user: process.env.MAIL_USER, pass: process.env.MAIL_PASS, }, tls: { rejectUnauthorized: false, }, }); const mailOptions = { from: `"${process.env.MAIL_FROM_NAME || "Coconut Trade Fair"}" <${process.env.MAIL_USER}>`, to: email, subject: title, html: template, attachments, }; if (cc !== "") mailOptions.cc = cc; transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log("mail error: " + error); // Reject on failure so callers can record a truthful `failed` status. // SMTP failures must never be converted into success. reject(error); } else { console.log(`Email sent: ${info.response} (${email})`); resolve(true); } }); }); }; Behavior of the mailer: * nodemailer receives the configured host, port, secure setting, and auth environment references. * It sends the generated HTML, subject, recipient, and attachments. * A successful transporter.sendMail callback resolves true. * A mail error rejects, allowing the caller to write email_logs.status = "failed" instead of treating the attempt as delivered. 6.4 Registration QR email template ----------------------------------- Source: templates/registration-qr-email.js Function: module.exports // hasHeader: when false (no public/event-header.png), the header image row is // omitted so the email never renders a broken image. module.exports = (name, eventTitle, ticketId, startDate, endDate, location, description, hasHeader = true) => { return `