Files
smart_grid_iot/server/src/middleware/auth.middleware.ts
T
andyesfly f4454ad014 feat: 新增电工APP端与定时任务管理功能
- 新增电工APP独立鉴权中间件与登录注册接口
- 新增定时任务管理模块,支持任务配置、执行日志与手动触发
- 新增运维费定价与电工派单成本价目管理
- 新增电工资质证照管理与到期提醒定时任务
- 完善数据库实体与DTO校验,优化权限控制
2026-10-02 16:08:00 +08:00

61 lines
1.6 KiB
TypeScript

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<Context, NextFunction> {
// 中间件匹配范围:全局生效,但跳过公开接口与电工 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();
};
}
}