import { Middleware, IMiddleware, Config } from '@midwayjs/core'; import { Context, NextFunction } from '@midwayjs/koa'; import { Provide, Inject } from '@midwayjs/core'; import { TokenUtil } from '../util/token'; @Provide() export class AuthMiddleware implements IMiddleware { // 中间件匹配范围:全局生效,但跳过公开接口与电工 APP 接口(电工 APP 走独立鉴权) ignore = ['/api/auth/*', '/api/health', '/api/worker-app/*']; @Inject() tokenUtil!: TokenUtil; resolve() { return async (ctx: Context, next: NextFunction) => { const authHeader = ctx.header.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { ctx.status = 401; ctx.body = { code: 401, message: '未提供认证令牌', }; return; } const token = authHeader.substring(7); let decoded: any; try { decoded = this.tokenUtil.verifyToken(token); } catch (error: any) { if (error.name === 'TokenExpiredError') { ctx.status = 401; ctx.body = { code: 401, message: '登录已过期,请重新登录', expired: true, }; } else { ctx.status = 401; ctx.body = { code: 401, message: '无效的认证令牌', }; } return; } ctx.state.user = { userId: decoded.userId, username: decoded.username, }; ctx.user = ctx.state.user; await next(); }; } }