27 lines
878 B
TypeScript
Raw Normal View History

2024-10-14 00:02:58 +08:00
import process from "node:process"
2024-10-14 01:20:43 +08:00
import { jwtVerify } from "jose"
2024-10-14 00:02:58 +08:00
2024-10-14 00:33:37 +08:00
export default defineEventHandler(async (event) => {
2024-10-14 17:18:57 +08:00
if (["JWT_SECRET", "G_CLIENT_ID", "G_CLIENT_SECRET"].find(k => !process.env[k])) {
2024-10-14 21:50:27 +08:00
event.context.disabledLogin = true
2024-10-14 17:18:57 +08:00
} else {
2024-10-14 21:50:27 +08:00
const url = getRequestURL(event)
if (/^\/(?:me|s)\//.test(url.pathname)) {
const token = getHeader(event, "Authorization")
if (token && process.env.JWT_SECRET) {
try {
const { payload } = await jwtVerify(token.replace("Bearer ", ""), new TextEncoder().encode(process.env.JWT_SECRET)) as { payload?: { id: string, type: string } }
if (payload?.id) {
event.context.user = {
id: payload.id,
type: payload.type,
}
}
} catch {
logger.error("JWT verification failed")
2024-10-14 17:18:57 +08:00
}
2024-10-14 01:20:43 +08:00
}
2024-10-14 00:02:58 +08:00
}
}
})