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.
This commit is contained in:
ethan.chen
2025-06-23 16:57:22 +08:00
parent e511ab9db6
commit 32f7b86f28
5 changed files with 59 additions and 9 deletions

29
auth.ts Normal file
View File

@@ -0,0 +1,29 @@
/*
* @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()
})