From eb6c3fe5eb12677521e8576c59ee693880c34dae Mon Sep 17 00:00:00 2001 From: beilunyang <786220806@qq.com> Date: Tue, 13 May 2025 00:01:15 +0800 Subject: [PATCH] feat: /api/config endpoint can be called using APIKey --- app/api/config/route.ts | 11 ++++++++++- app/lib/apiKey.ts | 2 +- app/lib/auth.ts | 8 +++++--- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/app/api/config/route.ts b/app/api/config/route.ts index 3cca76d..76499d8 100644 --- a/app/api/config/route.ts +++ b/app/api/config/route.ts @@ -1,6 +1,7 @@ -import { Role, ROLES } from "@/lib/permissions" +import { PERMISSIONS, Role, ROLES } from "@/lib/permissions" import { getRequestContext } from "@cloudflare/next-on-pages" import { EMAIL_CONFIG } from "@/config" +import { checkPermission } from "@/lib/auth" export const runtime = "edge" @@ -22,6 +23,14 @@ export async function GET() { } export async function POST(request: Request) { + const canAccess = await checkPermission(PERMISSIONS.MANAGE_CONFIG) + + if (!canAccess) { + return Response.json({ + error: "权限不足" + }, { status: 403 }) + } + const { defaultRole, emailDomains, adminContact, maxEmails } = await request.json() as { defaultRole: Exclude, emailDomains: string, diff --git a/app/lib/apiKey.ts b/app/lib/apiKey.ts index 28dce30..659e41d 100644 --- a/app/lib/apiKey.ts +++ b/app/lib/apiKey.ts @@ -25,7 +25,7 @@ async function getUserByApiKey(key: string): Promise { } export async function handleApiKeyAuth(apiKey: string, pathname: string) { - if (!pathname.startsWith('/api/emails')) { + if (!pathname.startsWith('/api/emails') && !pathname.startsWith('/api/config')) { return NextResponse.json( { error: "无权限查看" }, { status: 403 } diff --git a/app/lib/auth.ts b/app/lib/auth.ts index c1f48cc..15a13ba 100644 --- a/app/lib/auth.ts +++ b/app/lib/auth.ts @@ -10,6 +10,7 @@ import CredentialsProvider from "next-auth/providers/credentials" import { hashPassword, comparePassword } from "@/lib/utils" import { authSchema } from "@/lib/validation" import { generateAvatarUrl } from "./avatar" +import { getUserId } from "./apiKey" const ROLE_DESCRIPTIONS: Record = { [ROLES.EMPEROR]: "皇帝(网站所有者)", @@ -62,12 +63,13 @@ export async function getUserRole(userId: string) { } export async function checkPermission(permission: Permission) { - const session = await auth() - if (!session?.user?.id) return false + const userId = await getUserId() + + if (!userId) return false const db = createDb() const userRoleRecords = await db.query.userRoles.findMany({ - where: eq(userRoles.userId, session.user.id), + where: eq(userRoles.userId, userId), with: { role: true }, })