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

73 lines
2.8 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');
/**
* 用户态接口(小程序 / Win 客户端 / SPA 共用)
*
* 鉴权:`middleware.apiAuth()` —— **只认 header 里的 user JWT**(`Authorization: Bearer <token>`,
* 也认 `X-Access-Token`),不看 cookie / session;用户令牌自带 `typ: 'user'`,
* 与设备令牌(`typ: 'scanner'`)互不通用。
*
* 小程序和 Win 客户端之所以共用一套路径:它们身份相同(都是「某个登录用户」),
* 区别只在登录入口;要区分用途请用 header(如 `X-Client: miniapp|win`),不要复制一套路径。
*/
class ClientWechatController extends Controller {
/**
* POST /api/wechat/confirm —— 把登录码断权给当前登录用户(触发电脑端/客户端登录)
*
* 典型用法(小程序):扫码拿到 `http://<域名>/wechat?spm=1.0.<码>.1`,把扫到的整串、
* `spm` 或 6 位 `code` 丢过来即可(接口自己抽码);后端把码断权给当前登录用户,
* 电脑端正在长轮询的请求会**立即**拿到 JWT 完成登录。
*
* 需要登录:**只看 header**(`Authorization: Bearer <user JWT>` 或 `X-Access-Token`),不认 cookie
* body: `{ code | spm }`,也支持 `?code=` / `?spm=`(JSON / 表单 / query 都行)
*
* 返回:成功 `data.status=confirmed`;失败时 body.status = bad_format(422) / expired(410) /
* used(410) / unauthorized(401) / forbidden(403)
*/
async confirm() {
const { ctx } = this;
const body = ctx.request.body || {};
const raw = body.code || body.spm || ctx.query.code || ctx.query.spm;
// 用户只从 header 令牌解析(middleware/api_auth.js 挂的),不从 session 取
const user = (ctx.locals && ctx.locals.user) || (ctx.state && ctx.state.user) || null;
const userId = user && user.id;
const code = ctx.service.wechatLogin.parseSpm(raw);
if (!code) {
ctx.status = 422;
ctx.body = {
ok: false,
status: 'bad_format',
message: `登录码格式不对(${Number(ctx.app.config.wechat.codeLength || 6)} 位数字 + 字母)`,
};
return;
}
const result = await ctx.service.wechatLogin.confirm(code, userId);
if (!result.ok) {
// 码不存在/已过期/已被用过 → 410;参数不全 → 422
ctx.status = result.reason === 'bad_param' ? 422 : 410;
ctx.body = { ok: false, status: result.reason, message: result.message };
return;
}
ctx.body = {
ok: true,
data: {
status: 'confirmed',
code,
spm: ctx.service.wechatLogin.spm(code),
user: {
id: userId,
username: (user && user.username) || null,
nickname: (user && user.nickname) || null,
},
},
};
}
}
module.exports = ClientWechatController;