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

188 lines
6.9 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 { Controller } = require('egg');
/** 邮箱格式(与页面版保持一致,宽松校验) */
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
/**
* web 用户端:登录 / 注册 / 找回密码 / 重置密码(**JSON 接口**,给前端 SPA 调)
*
* 鉴权走 **header 令牌**(`Authorization: Bearer <user JWT>`),不依赖 cookie/session:
* 前端与后端不同源也没问题,也天然不受 CSRF 影响(`/api/*` 不过 CSRF)。
*
* 统一响应:成功 `{ ok:true, data }`;失败 `{ ok:false, status?, message }`。
*/
class WebAuthController extends Controller {
/** 签发令牌 + 返回脱敏用户(登录 / 注册成功后都走它) */
issue(user) {
const { ctx } = this;
return {
token: ctx.service.jwt.signUser(user),
tokenType: 'Bearer',
expiresIn: ctx.app.config.jwt.userExpiresIn,
user,
};
}
/**
* POST /api/web/auth/login
* body: `{ account, password }`(account 支持 用户名 / 手机号 / 邮箱)
* → `{ token, tokenType, expiresIn, user }`
*/
async login() {
const { ctx } = this;
const { account, password } = ctx.request.body || {};
if (!account || !password) {
ctx.status = 422;
ctx.body = { ok: false, message: '请填写账号和密码' };
return;
}
const user = await ctx.service.auth.login(String(account).trim(), password);
if (!user) {
ctx.status = 401;
ctx.body = { ok: false, status: 'unauthorized', message: '账号或密码错误' };
return;
}
ctx.logger.info('[web] %s 登录成功(API)', user.username || account);
ctx.body = { ok: true, data: this.issue(user) };
}
/**
* POST /api/web/auth/register/code
* body: `{ email }` → 发 6 位邮箱验证码(开发模式直接返回 `code`)
*/
async sendRegisterCode() {
const { ctx } = this;
const email = String((ctx.request.body || {}).email || '').trim().toLowerCase();
if (!ctx.app.config.register.enable) {
ctx.throw(403, '注册已关闭,请联系管理员开通账号');
}
if (!EMAIL_RE.test(email)) {
ctx.throw(422, '请填写正确的邮箱');
}
const exists = await ctx.service.user.findOneBy({ email });
if (exists) ctx.throw(409, '该邮箱已被使用');
const result = await ctx.service.verifyCode.send('register', email);
if (!result.ok) ctx.throw(429, result.message);
ctx.logger.info('[web] 注册验证码已发送到 %s', email);
ctx.body = {
ok: true,
data: {
email,
// 开发模式(未配 SMTP)把验证码带回来,前端可直接提示;生产不返回
devMode: Boolean(result.devMode),
code: result.devMode ? result.code : undefined,
},
};
}
/**
* POST /api/web/auth/register
* body: `{ username, email, code, password, nickname?, phone? }` → 建成即登录(返回令牌)
*/
async register() {
const { ctx } = this;
const body = ctx.request.body || {};
const username = String(body.username || '').trim();
const email = String(body.email || '').trim().toLowerCase();
const code = String(body.code || '').trim();
const password = String(body.password || '');
const nickname = String(body.nickname || '').trim();
const phone = String(body.phone || '').trim();
if (!ctx.app.config.register.enable) ctx.throw(403, '注册已关闭,请联系管理员开通账号');
if (!/^[A-Za-z0-9_]{3,32}$/.test(username)) ctx.throw(422, '用户名需 3-32 位字母、数字或下划线');
if (!EMAIL_RE.test(email)) ctx.throw(422, '邮箱格式不正确');
if (!/^\d{6}$/.test(code)) ctx.throw(422, '请填写 6 位邮箱验证码');
if (password.length < 6) ctx.throw(422, '密码至少 6 位');
if (phone && !/^[0-9+\-]{6,20}$/.test(phone)) ctx.throw(422, '手机号格式不正确');
const checked = await ctx.service.verifyCode.check('register', email, code);
if (!checked.ok) ctx.throw(422, checked.message);
try {
const user = await ctx.service.auth.register({ username, password, nickname, email, phone: phone || null });
// 注册成功才消费验证码(用户名/邮箱冲突时可改完重提,不用重新收码)
await ctx.service.verifyCode.consume('register', email);
ctx.logger.info('[web] %s 注册成功(API,id=%s)', username, user.id);
ctx.body = { ok: true, data: this.issue(user) };
} catch (err) {
// 唯一键冲突(409):翻成页面能直接显示的文案
if (err.status === 409) {
const message = String(err.message || '');
ctx.status = 409;
ctx.body = {
ok: false,
message: message.startsWith('username') ? '该用户名已被使用'
: message.startsWith('email') ? '该邮箱已被使用'
: message.startsWith('phone') ? '该手机号已被注册'
: '注册失败,请稍后重试',
};
return;
}
throw err;
}
}
/**
* POST /api/web/auth/forgot
* body: `{ email }` → 发重置链接(**防账号枚举**:邮箱没注册也返回成功)
*/
async forgot() {
const { ctx } = this;
const email = String((ctx.request.body || {}).email || '').trim().toLowerCase();
if (!EMAIL_RE.test(email)) ctx.throw(422, '请填写正确的邮箱');
const user = await ctx.service.user.findOneBy({ email });
if (user && Number(user.status) === 1) {
const origin = ctx.app.config.email.siteUrl || ctx.origin;
const result = await ctx.service.passwordReset.send(user, origin);
if (!result.ok) ctx.throw(500, result.message);
ctx.logger.info('[web] 已向 %s 发送重置密码链接', email);
ctx.body = {
ok: true,
data: {
sent: true,
// 开发模式(未配 SMTP)把链接返回,前端可直接点开
devMode: Boolean(result.devMode),
url: result.devMode ? result.url : undefined,
},
};
return;
}
if (user) ctx.logger.warn('[web] 账号已禁用,不发送重置链接: %s', email);
ctx.body = { ok: true, data: { sent: true } };
}
/**
* POST /api/web/auth/reset
* body: `{ token, password }` → 用邮件里的令牌设新密码(令牌一次性)
*/
async reset() {
const { ctx } = this;
const body = ctx.request.body || {};
const token = String(body.token || '');
const password = String(body.password || '');
const userId = await ctx.service.passwordReset.verify(token);
if (!userId) ctx.throw(410, '重置链接无效或已过期,请重新获取');
if (password.length < 6) ctx.throw(422, '密码至少 6 位');
await ctx.service.auth.setPassword(userId, password);
await ctx.service.passwordReset.consume(token, userId);
ctx.logger.info('[web] 用户 %s 通过邮件链接重置了密码(API)', userId);
ctx.body = { ok: true, data: { id: userId } };
}
}
module.exports = WebAuthController;