oms/backend/app/lib/emailCode.js

195 lines
5.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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 邮箱
* @return {String} redis key
*/
function codeKey(email) {
return `oms:email:code:${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}`;
}
/**
* 生成 6 位数字验证码
* @return {String} 验证码
*/
function generateCode() {
return String(Math.floor(100000 + Math.random() * 900000));
}
/**
* 记录邮件发送日志
* @param {Egg.Application} app egg application
* @param {Object} data 日志数据
* @return {Promise<void>} 无返回值
*/
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<String>} 受限原因,空字符串表示通过
*/
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<void>} 无返回值
*/
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
* @return {Promise<Object>} { ok: 是否发送成功, message: 失败原因 }
*/
async function sendCode(app, email, options = {}) {
const { userId = null, ip = '', scene = 'register' } = options;
const limitMessage = await checkLimit(app, email);
if (limitMessage) {
await writeLog(app, {
scene,
to_email: email,
subject: SUBJECT,
content: '',
user_id: userId,
ip,
status: 0,
error_msg: limitMessage,
});
return { ok: false, message: limitMessage };
}
const code = generateCode();
const content = `您的注册验证码为:${code},${CODE_TTL / 60} 分钟内有效。`;
await app.redis.set(codeKey(email), 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: SUBJECT,
text: content,
});
} catch (err) {
errorMsg = err.message;
app.logger.error(`[email-code] 邮件发送失败:${errorMsg}`);
}
}
await writeLog(app, {
scene,
to_email: email,
subject: 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 验证码
* @return {Promise<Boolean>} 校验是否通过
*/
async function verifyCode(app, email, code) {
const cached = await app.redis.get(codeKey(email));
if (!cached || cached !== String(code)) return false;
await app.redis.del(codeKey(email));
return true;
}
module.exports = {
CODE_TTL,
codeKey,
intervalKey,
dailyKey,
sendCode,
verifyCode,
};