import jwt from 'jsonwebtoken' import * as log4js from '../log4js.js' const whiteList = [ '/', '/api/login', '/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 { log4js.koa.debug(`鉴权: ${ctx.method} ${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 || 'chuanqi_secret') await next() } catch (err) { ctx.status = 401 ctx.body = { code: 401, message: 'token无效或过期,请重新登录' } } } export default auth