diff --git a/.env.example b/.env.example index bcd2e33..fe856a8 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/server/middleware/auth.ts b/server/middleware/auth.ts new file mode 100644 index 0000000..eab6905 --- /dev/null +++ b/server/middleware/auth.ts @@ -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) + } +})