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

57 lines
2.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';
/**
* 接口鉴权(**只认 header 里的令牌,不看 cookie/session**)
*
* 用法:`router.post('/api/xxx', middleware.apiAuth(), controller.xxx.yyy)`
*
* - 令牌:`Authorization: Bearer <user JWT>`(也认 `X-Access-Token`,方便不爱用 Authorization 的客户端)
* JWT 由这些地方下发:扫码登录 `GET /api/wechat/login` 的 `data.token`、页面里现场签发的同款令牌;
* - 不加 cookie、也不写 session:小程序 / App / SPA 这类没有浏览器 cookie 的客户端直接用它;
* - 未带或验不过 → 401 `{ ok:false, status:'unauthorized', message }`;
* 用户不存在/被禁用 → 403 `{ ok:false, status:'forbidden', message }`;
* - 通过后把用户放进 `ctx.locals.user` 与 `ctx.state.user`。
*/
module.exports = () => {
return async function apiAuth(ctx, next) {
const token = bearerToken(ctx);
const payload = token && ctx.service.jwt.verifyUser(token);
const userId = payload && payload.sub ? Number(payload.sub) : 0;
if (!userId) {
ctx.status = 401;
ctx.body = {
ok: false,
status: 'unauthorized',
message: '缺少或无效的令牌(请在 header 里带 Authorization: Bearer <token>)',
};
return;
}
const user = await ctx.service.user.findById(userId);
if (!user) {
ctx.status = 401;
ctx.body = { ok: false, status: 'unauthorized', message: '令牌对应的用户不存在' };
return;
}
if (Number(user.status) !== 1) {
ctx.status = 403;
ctx.body = { ok: false, status: 'forbidden', message: '账号已被禁用' };
return;
}
// 注意:**不碰 session/cookie**,接口鉴权完全基于这一次请求的 header
ctx.locals = ctx.locals || {};
ctx.locals.user = user;
ctx.state.user = user;
await next();
};
};
/** 取 header 里的令牌:优先 Authorization: Bearer,其次 X-Access-Token */
function bearerToken(ctx) {
const matched = /^Bearer\s+(.+)$/i.exec(ctx.get('authorization') || '');
if (matched) return matched[1].trim();
return String(ctx.get('x-access-token') || '').trim();
}