oms/backend/app/lib/emailCode.js
liufumingren 8597cf5ac9 feat(backend): 用户鉴权、菜单权限、主体与系统基础模块
- 登录/邮箱验证码/密码流程(controller/auth.js、lib/emailCode.js、middleware/jwt_auth.js)
- 主体(principal)隔离与主体用户、对外接口配置模块及 principalCheck 中间件
- 菜单、用户、文件上传、快递公司字典(express_companies)等基础模块
- 通用工具:分页(lib/pagination.js)、缓存(service/cache.js)
- 全量接口契约(contract/index.js)与路由注册(router.js)、config.default.js 配置
- 相关迁移:菜单组件调整与菜单种子、创建 files 表
2026-09-13 02:23:34 +08:00

206 lines
5.6 KiB
JavaScript
Raw Permalink 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 邮箱
* @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<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、length(验证码位数,默认6)、subject
* @return {Promise<Object>} { 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<Boolean>} 校验是否通过
*/
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,
};