Files
score-backend/auth.ts
ethan.chen 32f7b86f28 feat: implement authentication middleware and routes
- Added `auth.ts` for JWT authentication middleware.
- Created `auth` route to handle authentication and token verification.
- Integrated authentication middleware into `media.ts` for protected routes.
- Updated `main.ts` to register the new authentication route.
2025-06-23 16:57:22 +08:00

29 lines
736 B
TypeScript

/*
* @Date: 2025-06-23 14:36:45
* @LastEditors: 陈子健
* @LastEditTime: 2025-06-23 14:37:26
* @FilePath: /my-score/honoback/auth.ts
*/
import { createMiddleware } from 'hono/factory'
import { verify } from 'hono/jwt'
const AUTH_SECRET = 'it-is-a-secret'
export const authMiddleware = createMiddleware(async (c, next) => {
const authHeader = c.req.header('Authorization')
if (!authHeader || !authHeader.startsWith('Basic ')) {
return c.json({ message: 'Unauthorized' }, 401)
}
const token = authHeader.substring(6).trim()
try {
const payload = await verify(token, AUTH_SECRET)
c.set('jwtPayload', payload)
} catch (error) {
return c.json({ message: 'Invalid token' }, 401)
}
await next()
})