2025-12-24 23:48:14 +08:00
|
|
|
import jwt from "jsonwebtoken";
|
|
|
|
|
import * as log4js from "../log4js.js";
|
|
|
|
|
|
|
|
|
|
const whiteList = [
|
|
|
|
|
'/',
|
|
|
|
|
'/api/login',
|
2025-12-25 00:46:56 +08:00
|
|
|
"/api/server/list"
|
2025-12-24 23:48:14 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
async function auth(ctx, next) {
|
|
|
|
|
try {
|
|
|
|
|
log4js.koa.debug("接口请求:", ctx.path)
|
|
|
|
|
if (whiteList.includes(ctx.path)) {
|
|
|
|
|
await next();
|
|
|
|
|
return; // 终止后续验证逻辑
|
|
|
|
|
}
|
|
|
|
|
const token = ctx.request.headers.authorization?.split(' ')[1];
|
|
|
|
|
if (!token) throw new Error('无token');
|
|
|
|
|
ctx.user = jwt.verify(token, process.env.SECRET_KEY);
|
|
|
|
|
await next();
|
|
|
|
|
} catch (err) {
|
|
|
|
|
ctx.status = 401;
|
|
|
|
|
ctx.body = {msg: 'token无效或过期', code: 401};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default auth;
|