feat: JWT 认证中间件

This commit is contained in:
MikiVL 2026-05-05 05:54:59 +08:00
parent 43b3ef82f2
commit 52a5a005a7
2 changed files with 29 additions and 0 deletions

View File

@ -1 +1,3 @@
ANTHROPIC_API_KEY=sk-ant-your-key-here ANTHROPIC_API_KEY=sk-ant-your-key-here
JWT_SECRET=change-this-to-a-random-secret
JWT_SECRET=change-this-to-a-random-secret

27
server/middleware/auth.ts Normal file
View File

@ -0,0 +1,27 @@
import { createMiddleware } from 'hono/factory'
import jwt from 'jsonwebtoken'
export type JwtPayload = { userId: string; username: string }
declare module 'hono' {
interface ContextVariableMap {
userId: string
username: string
}
}
export const requireAuth = createMiddleware(async (c, next) => {
const header = c.req.header('Authorization')
if (!header?.startsWith('Bearer ')) {
return c.json({ error: '未登录' }, 401)
}
const token = header.slice(7)
try {
const payload = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload
c.set('userId', payload.userId)
c.set('username', payload.username)
await next()
} catch {
return c.json({ error: 'Token 无效或已过期' }, 401)
}
})