feat: JWT 认证中间件
This commit is contained in:
parent
43b3ef82f2
commit
52a5a005a7
@ -1 +1,3 @@
|
||||
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
27
server/middleware/auth.ts
Normal 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)
|
||||
}
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user