'use strict'; const TOKEN_PREFIX = 'Bearer '; /** * JWT 鉴权中间件 * 校验请求头 Authorization: Bearer ,解析出 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(); }; };