packServer/backend/app/service/verify_code.js
liufumingren bd2363bf00 chore: 初始化仓库(backend / frontend / extension 三块)
- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权;
  已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF),
  开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。
  单测 91 个通过(不需要本机数据库)。
- frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 /
  首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。
- extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。
- 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、
  .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
2026-10-17 08:50:32 +08:00

117 lines
4.2 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 { Service } = require('egg');
/** 场景 → Redis key 段(不同场景的验证码互不影响) */
const SCENES = { register: 'verify:register' };
/** 6 位数字验证码 */
function randomCode() {
return String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
}
/**
* 邮箱验证码:生成 / 校验 / 消费
*
* 存在 Redis:
* - `packs:verify:<scene>:<email>` 验证码本身(TTL = config.email.codeTtl,默认 10 分钟)
* - `packs:verify:<scene>:<email>:sent` 重发节流标记(SET NX,TTL = resendInterval,默认 60 秒)
* - `packs:verify:<scene>:<email>:try` 错误次数(超过 maxAttempts 作废验证码)
*
* 对外不抛异常,统一返回 `{ ok, message }`,方便页面回提示(不弹 500)。
*/
class VerifyCodeService extends Service {
get redis() {
return this.app.redis;
}
get cfg() {
return this.app.config.email;
}
keyOf(scene, email) {
const segment = SCENES[scene] || scene;
return `${this.app.config.cache.prefix}${segment}:${email}`;
}
/**
* 生成验证码并发邮件
* @param {string} scene 场景(register)
* @param {string} email 邮箱(调用方保证已小写归一)
* @return {Promise<{ok:boolean, message?:string, code?:string, devMode?:boolean, ttl?:number, resendInterval?:number}>}
*/
async send(scene, email) {
if (!this.redis) return { ok: false, message: '验证码服务不可用(Redis 未就绪)' };
const key = this.keyOf(scene, email);
try {
// 重发节流:SET NX 原子占位,间隔内只允许发一次
const locked = await this.redis.set(`${key}:sent`, '1', 'EX', this.cfg.resendInterval, 'NX');
if (locked !== 'OK') {
return { ok: false, message: `验证码已发送,请 ${this.cfg.resendInterval} 秒后再试` };
}
const code = randomCode();
await this.redis.setex(key, this.cfg.codeTtl, code);
await this.redis.del(`${key}:try`);
const mail = await this.ctx.service.mail.sendVerifyCode(email, code, { ttl: this.cfg.codeTtl });
if (mail.failed) {
await this.redis.del(`${key}:sent`); // 发失败就不要占着节流位
return { ok: false, message: '验证码邮件发送失败,请稍后再试' };
}
this.ctx.logger.info('[verify] %s 验证码已生成: %s (devMode=%s)', scene, email, !!mail.devMode);
return {
ok: true,
ttl: this.cfg.codeTtl,
resendInterval: this.cfg.resendInterval,
devMode: !!mail.devMode,
// 开发模式才把验证码回传给页面(生产走邮件)
code: mail.devMode ? code : undefined,
};
} catch (err) {
this.ctx.logger.error('[verify] 验证码发送失败 %s : %s', email, err.message);
return { ok: false, message: '验证码服务暂不可用,请稍后再试' };
}
}
/**
* 校验验证码(不消费,注册成功后再 consume,这样用户名冲突时可以改完重提)
* @return {Promise<{ok:boolean, message?:string}>}
*/
async check(scene, email, code) {
if (!this.redis) return { ok: false, message: '验证码服务不可用(Redis 未就绪)' };
const key = this.keyOf(scene, email);
try {
const expect = await this.redis.get(key);
if (!expect) return { ok: false, message: '验证码已过期,请重新获取' };
const tries = await this.redis.incr(`${key}:try`);
await this.redis.expire(`${key}:try`, this.cfg.codeTtl);
if (tries > this.cfg.maxAttempts) {
await this.redis.del(key);
return { ok: false, message: '验证码错误次数过多,请重新获取' };
}
if (String(code) !== String(expect)) {
return { ok: false, message: '邮箱验证码不正确' };
}
return { ok: true };
} catch (err) {
this.ctx.logger.error('[verify] 验证码校验失败 %s : %s', email, err.message);
return { ok: false, message: '验证码服务暂不可用,请稍后再试' };
}
}
/** 消费掉验证码(注册成功后调用) */
async consume(scene, email) {
if (!this.redis) return;
const key = this.keyOf(scene, email);
await this.redis.del(key);
await this.redis.del(`${key}:try`);
}
}
module.exports = VerifyCodeService;