33 lines
1.3 KiB
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-15 12:05:03 +08:00
const url = getRequestURL(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-24 20:50:30 +08:00
if (!url.pathname.startsWith("/api/s"))
throw createError({ statusCode: 506, message: "Server not configured, disable login" })
2024-10-14 17:18:57 +08:00
} else {
2024-10-24 20:50:30 +08:00
if (["/api/s", "/api/me"].find(p => url.pathname.startsWith(p))) {
2024-10-25 03:06:28 +08:00
const token = getHeader(event, "Authorization")?.replace(/Bearer\s*/, "")?.trim()
2024-10-24 20:50:30 +08:00
if (token) {
2024-10-14 21:50:27 +08:00
try {
2024-10-19 13:14:31 +08:00
const { payload } = await jwtVerify(token, new TextEncoder().encode(process.env.JWT_SECRET)) as { payload?: { id: string, type: string } }
2024-10-14 21:50:27 +08:00
if (payload?.id) {
event.context.user = {
id: payload.id,
type: payload.type,
}
}
} catch {
2024-10-24 20:50:30 +08:00
if (url.pathname.startsWith("/api/me"))
throw createError({ statusCode: 401, message: "JWT verification failed" })
else logger.warn("JWT verification failed")
2024-10-14 17:18:57 +08:00
}
2024-10-24 20:50:30 +08:00
} else if (url.pathname.startsWith("/api/me")) {
throw createError({ statusCode: 401, message: "JWT verification failed" })
2024-10-14 01:20:43 +08:00
}
2024-10-14 00:02:58 +08:00
}
}
})