oms/backend/app/middleware/jwt_auth.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

63 lines
1.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 TOKEN_PREFIX = 'Bearer ';
/**
* JWT 鉴权中间件
* 校验请求头 Authorization: Bearer <token>,解析出 user_id 后加载用户信息(Redis 缓存优先,避免频繁查库),
* 并把用户信息与其可用主体ID列表挂载到 ctx,供控制器与后续中间件复用
* @return {Function} koa 中间件
*/
module.exports = () => {
return async (ctx, next) => {
const app = ctx.app;
const header = ctx.get('authorization') || '';
const token = header.startsWith(TOKEN_PREFIX) ? header.slice(TOKEN_PREFIX.length) : header;
if (!token) {
ctx.status = 401;
ctx.body = { code: 401, message: '缺少登录凭证,请先登录' };
return;
}
// 仅校验 token 本身,不要把控制器(await next)抛出的业务异常也吞成 401
let decoded;
try {
// token 载荷仅包含 user_id,不含任何敏感信息
decoded = app.jwt.verify(token, app.config.jwt.secret);
} catch (err) {
ctx.status = 401;
ctx.body = { code: 401, message: '登录凭证无效或已过期' };
return;
}
const userId = decoded.user_id;
// 用户信息与可用主体ID均走缓存,命中时不再查库
const [ user, principalIds ] = await Promise.all([
ctx.service.cache.getUser(userId),
ctx.service.cache.getUserPrincipalIds(userId),
]);
if (!user) {
ctx.status = 401;
ctx.body = { code: 401, message: '用户不存在或已被删除' };
return;
}
if (Number(user.status) !== 1) {
ctx.status = 403;
ctx.body = { code: 403, message: '账号已禁用' };
return;
}
ctx.userId = userId;
ctx.state.userId = userId;
ctx.user = user;
ctx.state.user = user;
ctx.userPrincipalIds = principalIds || [];
ctx.state.principalIds = principalIds || [];
await next();
};
};