'use strict'; const nodemailer = require('nodemailer'); /** 验证码有效期:10 分钟 */ const CODE_TTL = 10 * 60; /** 每日计数缓存时间:24 小时 */ const DAY_TTL = 24 * 60 * 60; /** 默认邮件主题(注册场景) */ const SUBJECT = 'OMS 注册邮箱验证码'; /** * 验证码在 Redis 中的 key(按场景隔离,避免注册与找回密码互串) * @param {String} email 邮箱 * @param {String} scene 场景:register 注册 / reset-password 找回密码 * @return {String} redis key */ function codeKey(email, scene = 'register') { return `oms:email:code:${scene}:${email}`; } /** * 发送间隔限制的 key * @param {String} email 邮箱 * @return {String} redis key */ function intervalKey(email) { return `oms:email:limit:interval:${email}`; } /** * 每日发送次数统计的 key(按自然日) * @param {String} email 邮箱 * @return {String} redis key */ function dailyKey(email) { const now = new Date(); const day = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; return `oms:email:limit:daily:${email}:${day}`; } /** * 生成指定位数的数字验证码 * @param {Number} len 位数,默认 6(找回密码场景为 4 位) * @return {String} 验证码 */ function generateCode(len = 6) { const min = 10 ** (len - 1); const max = 10 ** len - 1; return String(Math.floor(min + Math.random() * (max - min + 1))); } /** * 记录邮件发送日志 * @param {Egg.Application} app egg application * @param {Object} data 日志数据 * @return {Promise} 无返回值 */ async function writeLog(app, data) { try { await app.model.EmailLog.create(data); } catch (err) { // 日志写入失败不应影响主流程 app.logger.error(`[email-code] 邮件日志写入失败:${err.message}`); } } /** * 检查发送频率是否超限 * @param {Egg.Application} app egg application * @param {String} email 邮箱 * @return {Promise} 受限原因,空字符串表示通过 */ async function checkLimit(app, email) { const { interval, dailyLimit } = app.config.emailCode; const [ locked, sent ] = await Promise.all([ app.redis.get(intervalKey(email)), app.redis.get(dailyKey(email)), ]); if (locked) return `发送过于频繁,请 ${interval} 秒后再试`; if (sent && Number(sent) >= dailyLimit) return `今日发送次数已达上限(${dailyLimit} 次),请明日再试`; return ''; } /** * 记录一次成功发送 * @param {Egg.Application} app egg application * @param {String} email 邮箱 * @return {Promise} 无返回值 */ async function markSent(app, email) { const { interval } = app.config.emailCode; await app.redis.set(intervalKey(email), '1', 'EX', interval); const dk = dailyKey(email); const count = await app.redis.incr(dk); if (count === 1) await app.redis.expire(dk, DAY_TTL); } /** * 发送邮箱验证码并缓存到 Redis(含频率限制与发送日志) * 未配置 SMTP(config.mailer.host 为空)时仅记录日志,便于本地开发调试 * @param {Egg.Application} app egg application * @param {String} email 目标邮箱 * @param {Object} options 附加信息:userId、ip、scene、length(验证码位数,默认6)、subject * @return {Promise} { ok: 是否发送成功, message: 失败原因 } */ async function sendCode(app, email, options = {}) { const { userId = null, ip = '', scene = 'register', length = 6, subject = SUBJECT, } = options; const limitMessage = await checkLimit(app, email); if (limitMessage) { await writeLog(app, { scene, to_email: email, subject, content: '', user_id: userId, ip, status: 0, error_msg: limitMessage, }); return { ok: false, message: limitMessage }; } const code = generateCode(length); const content = `您的验证码为:${code},${CODE_TTL / 60} 分钟内有效。`; await app.redis.set(codeKey(email, scene), code, 'EX', CODE_TTL); let errorMsg = ''; const mailer = app.config.mailer; if (!mailer.host) { app.logger.info(`[email-code] 未配置 SMTP,邮箱 ${email} 的验证码为:${code}`); } else { try { const transporter = nodemailer.createTransport({ host: mailer.host, port: mailer.port, secure: mailer.secure, auth: mailer.auth, }); await transporter.sendMail({ from: mailer.from, to: email, subject, text: content, }); } catch (err) { errorMsg = err.message; app.logger.error(`[email-code] 邮件发送失败:${errorMsg}`); } } await writeLog(app, { scene, to_email: email, subject, content, user_id: userId, ip, status: errorMsg ? 0 : 1, error_msg: errorMsg || null, }); if (errorMsg) return { ok: false, message: '邮件发送失败,请稍后重试' }; await markSent(app, email); return { ok: true, message: '' }; } /** * 校验邮箱验证码,通过后立即失效 * @param {Egg.Application} app egg application * @param {String} email 邮箱 * @param {String} code 验证码 * @param {String} scene 场景:register 注册 / reset-password 找回密码 * @return {Promise} 校验是否通过 */ async function verifyCode(app, email, code, scene = 'register') { const cached = await app.redis.get(codeKey(email, scene)); if (!cached || cached !== String(code)) return false; await app.redis.del(codeKey(email, scene)); return true; } module.exports = { CODE_TTL, codeKey, intervalKey, dailyKey, sendCode, verifyCode, };