Files
chuanqi-qycq-web/module/server/koa/auth.js

39 lines
1.0 KiB
JavaScript
Raw Normal View History

2026-03-16 12:05:55 +08:00
import jwt from 'jsonwebtoken'
import * as log4js from '../log4js.js'
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 反查账号
]
async function auth(ctx, next) {
try {
2026-03-16 12:05:55 +08:00
log4js.koa.debug(`鉴权: ${ctx.method} ${ctx.path}`)
if (whiteList.includes(ctx.path)) {
2026-03-16 12:05:55 +08:00
await next()
return
}
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()
} catch (err) {
2026-03-16 12:05:55 +08:00
ctx.status = 401
ctx.body = { code: 401, message: 'token无效或过期请重新登录' }
}
}
2026-03-16 12:05:55 +08:00
export default auth