2026-03-16 12:05:55 +08:00
|
|
|
|
import jwt from 'jsonwebtoken'
|
|
|
|
|
|
import * as log4js from '../log4js.js'
|
2025-12-24 23:48:14 +08:00
|
|
|
|
|
|
|
|
|
|
const whiteList = [
|
|
|
|
|
|
'/',
|
|
|
|
|
|
'/api/login',
|
2026-03-16 12:05:55 +08:00
|
|
|
|
'/api/register',
|
|
|
|
|
|
'/api/send_code',
|
|
|
|
|
|
'/api/reset_password',
|
|
|
|
|
|
'/api/check', // 旧版 token 验证,无需 JWT
|
|
|
|
|
|
'/api/server/list',
|
|
|
|
|
|
'/api/misc/agree',
|
|
|
|
|
|
'/api/config',
|
|
|
|
|
|
'/api/linuxdo/authorize',
|
|
|
|
|
|
'/api/linuxdo/callback',
|
|
|
|
|
|
'/api/linuxdo/bind',
|
|
|
|
|
|
'/api/bind_account', // 游戏服务端内部:绑定第三方账号
|
|
|
|
|
|
'/api/link', // 游戏服务端内部:按 connect_id 反查账号
|
2025-12-24 23:48:14 +08:00
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
async function auth(ctx, next) {
|
|
|
|
|
|
try {
|
2026-03-16 12:05:55 +08:00
|
|
|
|
log4js.koa.debug(`鉴权: ${ctx.method} ${ctx.path}`)
|
2025-12-24 23:48:14 +08:00
|
|
|
|
if (whiteList.includes(ctx.path)) {
|
2026-03-16 12:05:55 +08:00
|
|
|
|
await next()
|
|
|
|
|
|
return
|
2025-12-24 23:48:14 +08:00
|
|
|
|
}
|
2026-03-16 12:05:55 +08:00
|
|
|
|
const token = ctx.request.headers.authorization?.split(' ')[1]
|
|
|
|
|
|
if (!token) throw new Error('无token')
|
|
|
|
|
|
ctx.user = jwt.verify(token, process.env.SECRET_KEY || 'chuanqi_secret')
|
|
|
|
|
|
await next()
|
2025-12-24 23:48:14 +08:00
|
|
|
|
} catch (err) {
|
2026-03-16 12:05:55 +08:00
|
|
|
|
ctx.status = 401
|
|
|
|
|
|
ctx.body = { code: 401, message: 'token无效或过期,请重新登录' }
|
2025-12-24 23:48:14 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-16 12:05:55 +08:00
|
|
|
|
export default auth
|