refactor: replace server action with API route for image uploads and update Nginx rate limiting configuration
This commit is contained in:
@@ -1,42 +0,0 @@
|
||||
"use server";
|
||||
|
||||
import { writeFile, mkdir } from "fs/promises";
|
||||
import path from "path";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
||||
|
||||
export async function uploadImage(formData: FormData): Promise<string> {
|
||||
const session = await getServerSession(authOptions);
|
||||
const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "")
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const discordId = (session?.user as { discordId?: string } | undefined)
|
||||
?.discordId;
|
||||
if (!discordId || !adminIds.includes(discordId)) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
const file = formData.get("file") as File;
|
||||
if (!file) throw new Error("No file provided");
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
throw new Error("Only image files are allowed");
|
||||
}
|
||||
|
||||
const allowedExtensions = ["png", "jpg", "jpeg", "webp", "gif"];
|
||||
const originalExt = (file.name.split(".").pop() || "").toLowerCase();
|
||||
|
||||
if (!allowedExtensions.includes(originalExt)) {
|
||||
throw new Error("Invalid image extension");
|
||||
}
|
||||
|
||||
const filename = `${crypto.randomUUID()}.${originalExt}`;
|
||||
const uploadDir = path.join(process.cwd(), "public", "form");
|
||||
|
||||
await mkdir(uploadDir, { recursive: true });
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
await writeFile(path.join(uploadDir, filename), buffer);
|
||||
|
||||
return `/form/${filename}`;
|
||||
}
|
||||
Reference in New Issue
Block a user