feat(admin): media library + upload component (replace URL fields)
- /admin/files Media Library: drag-drop multi-upload, thumbnails, copy-URL, delete - FileUploadField replaces raw URL inputs; new "image" field type in AdminResource; wired into category image - upload proxy /api/admin/files/upload: browser → Next → presigned PUT (server-side, reaches minio:9000) → confirm → returns public URL - user-uploads bucket is public-read; public base via NEXT_PUBLIC_MINIO_URL Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -33,6 +33,8 @@ ARG NEXT_PUBLIC_SITE_URL=http://localhost:3000
|
||||
# V2: browser-facing gateway base (host-exposed port) + tenant for Identity auth
|
||||
ARG NEXT_PUBLIC_API_URL=http://localhost:8088/v1
|
||||
ARG NEXT_PUBLIC_TENANT_SLUG=flatrender
|
||||
# Browser-reachable MinIO base for public (user-uploads) object URLs.
|
||||
ARG NEXT_PUBLIC_MINIO_URL=http://localhost:9000
|
||||
|
||||
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL
|
||||
ENV NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
@@ -40,6 +42,7 @@ ENV NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=$NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
|
||||
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
|
||||
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||
ENV NEXT_PUBLIC_TENANT_SLUG=$NEXT_PUBLIC_TENANT_SLUG
|
||||
ENV NEXT_PUBLIC_MINIO_URL=$NEXT_PUBLIC_MINIO_URL
|
||||
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
ENV NODE_ENV=production
|
||||
|
||||
@@ -276,6 +276,7 @@ services:
|
||||
# V2 gateway: browser-facing base (host port) baked in at build time.
|
||||
NEXT_PUBLIC_API_URL: "${NEXT_PUBLIC_API_URL:-http://localhost:${GATEWAY_PORT:-8080}/v1}"
|
||||
NEXT_PUBLIC_TENANT_SLUG: "${NEXT_PUBLIC_TENANT_SLUG:-flatrender}"
|
||||
NEXT_PUBLIC_MINIO_URL: "${NEXT_PUBLIC_MINIO_URL:-http://localhost:9000}"
|
||||
container_name: fr2-frontend
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
|
||||
+2
-1
@@ -320,7 +320,8 @@
|
||||
"slides": "Slides",
|
||||
"users": "Users",
|
||||
"plans": "Plans",
|
||||
"templates": "Templates"
|
||||
"templates": "Templates",
|
||||
"media": "Media"
|
||||
},
|
||||
"appAdminNodesPage": {
|
||||
"title": "Render Nodes",
|
||||
|
||||
+2
-1
@@ -320,7 +320,8 @@
|
||||
"slides": "اسلایدها",
|
||||
"users": "کاربران",
|
||||
"plans": "پلنها",
|
||||
"templates": "قالبها"
|
||||
"templates": "قالبها",
|
||||
"media": "رسانه"
|
||||
},
|
||||
"appAdminNodesPage": {
|
||||
"title": "نودهای رندر",
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { FileManager } from "@/components/admin/FileManager";
|
||||
|
||||
export default function Page() {
|
||||
return <FileManager />;
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export default async function AdminLayout({
|
||||
{ href: "/admin/fonts", label: t("fonts") },
|
||||
{ href: "/admin/blogs", label: t("blogs") },
|
||||
{ href: "/admin/slides", label: t("slides") },
|
||||
{ href: "/admin/files", label: t("media") },
|
||||
{ href: "/admin/ai", label: t("aiContent") },
|
||||
{ href: "/admin/users", label: t("users") },
|
||||
{ href: "/admin/plans", label: t("plans") },
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { type NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { gatewayUrl } from "@/lib/api/gateway";
|
||||
import { getAccessToken } from "@/lib/auth/session";
|
||||
import { decodeJwt } from "@/lib/auth/jwt";
|
||||
import { MINIO_PUBLIC_URL } from "@/lib/files";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Browser → Next → MinIO upload proxy. The browser can't reach the presigned MinIO
|
||||
* host (minio:9000) directly, but the Next server (in the docker network) can. So:
|
||||
* 1. ask file-svc for a presigned PUT URL
|
||||
* 2. PUT the bytes server-side
|
||||
* 3. confirm the upload
|
||||
* 4. return the public object URL (user-uploads bucket is public-read)
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const token = await getAccessToken();
|
||||
if (!token) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
const claims = decodeJwt(token);
|
||||
const isAdmin =
|
||||
String(claims?.is_admin) === "true" || claims?.is_admin === true ||
|
||||
String(claims?.is_tenant_admin) === "true";
|
||||
if (!isAdmin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
|
||||
const form = await req.formData().catch(() => null);
|
||||
const file = form?.get("file");
|
||||
if (!(file instanceof File)) {
|
||||
return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
||||
}
|
||||
|
||||
const auth = { Authorization: `Bearer ${token}` };
|
||||
|
||||
// 1. presigned PUT URL
|
||||
const presignRes = await fetch(gatewayUrl("/v1/files/presigned-upload"), {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { ...auth, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
filename: file.name,
|
||||
mime_type: file.type || "application/octet-stream",
|
||||
size_bytes: file.size,
|
||||
}),
|
||||
});
|
||||
const presign = await presignRes.json().catch(() => null);
|
||||
if (!presignRes.ok || !presign?.upload_url || !presign?.file_id) {
|
||||
return NextResponse.json(
|
||||
{ error: presign?.error?.message ?? "Could not start upload" },
|
||||
{ status: presignRes.status || 502 }
|
||||
);
|
||||
}
|
||||
|
||||
// 2. PUT the bytes to MinIO (server-side; reaches minio:9000)
|
||||
const put = await fetch(presign.upload_url, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": file.type || "application/octet-stream" },
|
||||
body: Buffer.from(await file.arrayBuffer()),
|
||||
});
|
||||
if (!put.ok) {
|
||||
return NextResponse.json({ error: "Upload to storage failed" }, { status: 502 });
|
||||
}
|
||||
|
||||
// 3. confirm
|
||||
await fetch(gatewayUrl(`/v1/files/${presign.file_id}/confirm`), {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: auth,
|
||||
});
|
||||
|
||||
// 4. fetch the record to get bucket/key → build the public URL
|
||||
const detailRes = await fetch(gatewayUrl(`/v1/files/${presign.file_id}`), {
|
||||
cache: "no-store",
|
||||
headers: auth,
|
||||
});
|
||||
const detail = await detailRes.json().catch(() => null);
|
||||
const bucket = detail?.minio_bucket ?? "user-uploads";
|
||||
const key = detail?.minio_key;
|
||||
const url = key ? `${MINIO_PUBLIC_URL}/${bucket}/${key}` : null;
|
||||
|
||||
return NextResponse.json({
|
||||
id: presign.file_id,
|
||||
name: file.name,
|
||||
mime_type: file.type,
|
||||
url,
|
||||
});
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
|
||||
import { FileUploadField } from "@/components/admin/FileUploadField";
|
||||
|
||||
export interface FieldDef {
|
||||
key: string;
|
||||
label: string;
|
||||
type?: "text" | "textarea" | "number" | "checkbox" | "select";
|
||||
type?: "text" | "textarea" | "number" | "checkbox" | "select" | "image" | "file";
|
||||
options?: { value: string; label: string }[];
|
||||
required?: boolean;
|
||||
placeholder?: string;
|
||||
@@ -215,6 +217,12 @@ export function AdminResource({ config }: { config: ResourceConfig }) {
|
||||
<input type="checkbox" checked={!!form[f.key]} onChange={(e) => setForm({ ...form, [f.key]: e.target.checked })} />
|
||||
{f.label}
|
||||
</label>
|
||||
) : f.type === "image" || f.type === "file" ? (
|
||||
<FileUploadField
|
||||
value={String(form[f.key] ?? "")}
|
||||
onChange={(url) => setForm({ ...form, [f.key]: url })}
|
||||
accept={f.type === "image" ? "image/*" : "*/*"}
|
||||
/>
|
||||
) : (
|
||||
<input type={f.type === "number" ? "number" : "text"} className={inputCls} placeholder={f.placeholder}
|
||||
value={String(form[f.key] ?? "")}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { MINIO_PUBLIC_URL } from "@/lib/files";
|
||||
|
||||
interface FileItem {
|
||||
id: string;
|
||||
name: string;
|
||||
mime_type?: string;
|
||||
file_type?: string;
|
||||
size_bytes?: number;
|
||||
minio_bucket?: string;
|
||||
minio_key?: string;
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
const card = "rounded-xl border border-[#1e2235] bg-[#0f1120]";
|
||||
const btn = "rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:opacity-50";
|
||||
|
||||
function fileUrl(f: FileItem): string | null {
|
||||
if (!f.minio_key) return null;
|
||||
return `${MINIO_PUBLIC_URL}/${f.minio_bucket ?? "user-uploads"}/${f.minio_key}`;
|
||||
}
|
||||
function isImage(f: FileItem): boolean {
|
||||
return (f.mime_type ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|svg|avif)$/i.test(f.name);
|
||||
}
|
||||
function humanSize(n?: number): string {
|
||||
if (!n) return "—";
|
||||
const u = ["B", "KB", "MB", "GB"]; let i = 0; let v = n;
|
||||
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
|
||||
return `${v.toFixed(v < 10 && i > 0 ? 1 : 0)} ${u[i]}`;
|
||||
}
|
||||
|
||||
export function FileManager() {
|
||||
const [files, setFiles] = useState<FileItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch("/api/admin/resource/files", { cache: "no-store" });
|
||||
const data = await res.json();
|
||||
setFiles(data?.data ?? data?.items ?? (Array.isArray(data) ? data : []));
|
||||
} catch {
|
||||
setError("Failed to load files");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { reload(); }, [reload]);
|
||||
|
||||
const uploadFiles = async (list: FileList) => {
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
for (const file of Array.from(list)) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch("/api/admin/files/upload", { method: "POST", body: fd });
|
||||
if (!res.ok) {
|
||||
const d = await res.json().catch(() => null);
|
||||
setError(d?.error ?? `Failed to upload ${file.name}`);
|
||||
}
|
||||
}
|
||||
setUploading(false);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
reload();
|
||||
};
|
||||
|
||||
const remove = async (f: FileItem) => {
|
||||
if (!confirm(`Delete ${f.name}?`)) return;
|
||||
const res = await fetch(`/api/admin/resource/files/${f.id}`, { method: "DELETE" });
|
||||
if (res.ok) reload(); else setError("Delete failed");
|
||||
};
|
||||
|
||||
const copy = (url: string) => {
|
||||
navigator.clipboard?.writeText(url);
|
||||
setCopied(url);
|
||||
setTimeout(() => setCopied(null), 1500);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-white">Media Library</h1>
|
||||
<p className="mt-1 text-sm text-gray-400">Upload and manage images & files. Public URLs can be copied into any field.</p>
|
||||
</div>
|
||||
<button className={btn} onClick={() => inputRef.current?.click()} disabled={uploading}>
|
||||
{uploading ? "Uploading…" : "+ Upload files"}
|
||||
</button>
|
||||
<input ref={inputRef} type="file" multiple className="hidden" onChange={(e) => e.target.files && uploadFiles(e.target.files)} />
|
||||
</div>
|
||||
|
||||
{error && <p className="rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-300">{error}</p>}
|
||||
|
||||
<div
|
||||
className={`${card} p-4`}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => { e.preventDefault(); if (e.dataTransfer.files.length) uploadFiles(e.dataTransfer.files); }}
|
||||
>
|
||||
{loading ? (
|
||||
<p className="py-10 text-center text-sm text-gray-500">Loading…</p>
|
||||
) : files.length === 0 ? (
|
||||
<p className="py-10 text-center text-sm text-gray-500">No files yet. Drag & drop here or click Upload.</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
|
||||
{files.map((f) => {
|
||||
const url = fileUrl(f);
|
||||
return (
|
||||
<div key={f.id} className="group rounded-lg border border-[#262b40] bg-[#0c0e1a] p-2">
|
||||
<div className="flex aspect-square items-center justify-center overflow-hidden rounded-md bg-[#070811]">
|
||||
{url && isImage(f) ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={url} alt={f.name} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<span className="text-[10px] uppercase text-gray-600">{(f.name.split(".").pop() ?? "file").slice(0, 5)}</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1.5 truncate text-[11px] text-gray-300" title={f.name}>{f.name}</p>
|
||||
<p className="text-[10px] text-gray-600">{humanSize(f.size_bytes)}</p>
|
||||
<div className="mt-1 flex gap-1">
|
||||
{url && (
|
||||
<button className="flex-1 rounded border border-[#262b40] px-1 py-0.5 text-[10px] text-gray-400 hover:bg-[#161a2e]" onClick={() => copy(url)}>
|
||||
{copied === url ? "Copied!" : "Copy URL"}
|
||||
</button>
|
||||
)}
|
||||
<button className="rounded border border-red-500/30 px-1.5 py-0.5 text-[10px] text-red-300 hover:bg-red-500/10" onClick={() => remove(f)}>Del</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
/** Upload-or-clear field that replaces a raw URL text input. Stores the public URL. */
|
||||
export function FileUploadField({
|
||||
value,
|
||||
onChange,
|
||||
accept = "image/*",
|
||||
label,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (url: string) => void;
|
||||
accept?: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isImage = value && /\.(png|jpe?g|gif|webp|svg|avif)$/i.test(value);
|
||||
|
||||
const upload = async (file: File) => {
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch("/api/admin/files/upload", { method: "POST", body: fd });
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data?.url) throw new Error(data?.error ?? "Upload failed");
|
||||
onChange(data.url);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Upload failed");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{label && <label className="mb-1 block text-xs font-medium text-gray-400">{label}</label>}
|
||||
<div className="flex items-center gap-3">
|
||||
{value ? (
|
||||
isImage ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={value} alt="" className="h-14 w-14 rounded-lg border border-[#262b40] object-cover" />
|
||||
) : (
|
||||
<span className="max-w-[160px] truncate rounded-lg border border-[#262b40] bg-[#0c0e1a] px-2 py-1 text-xs text-gray-400">
|
||||
{value.split("/").pop()}
|
||||
</span>
|
||||
)
|
||||
) : (
|
||||
<span className="flex h-14 w-14 items-center justify-center rounded-lg border border-dashed border-[#262b40] text-[10px] text-gray-600">
|
||||
none
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) upload(f);
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={uploading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:opacity-50"
|
||||
>
|
||||
{uploading ? "Uploading…" : value ? "Replace" : "Upload"}
|
||||
</button>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange("")}
|
||||
className="rounded-lg border border-[#262b40] px-3 py-1.5 text-xs text-gray-400 hover:bg-[#161a2e]"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="mt-1 text-xs text-red-400">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -51,7 +51,7 @@ export const categoriesConfig: ResourceConfig = {
|
||||
{ key: "name", label: "Name", required: true },
|
||||
{ key: "slug", label: "Slug", required: true },
|
||||
{ key: "description", label: "Description / content", type: "textarea" },
|
||||
{ key: "image_url", label: "Image URL" },
|
||||
{ key: "image_url", label: "Image", type: "image" },
|
||||
{ key: "icon", label: "Icon" },
|
||||
// SEO
|
||||
{ key: "meta_title", label: "SEO · Meta title" },
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Public base URL for objects in the (public-read) user-uploads MinIO bucket.
|
||||
* Must be browser-reachable (MinIO is published on :9000). Configure per deployment
|
||||
* via NEXT_PUBLIC_MINIO_URL; falls back to localhost for local dev.
|
||||
*/
|
||||
export const MINIO_PUBLIC_URL = (
|
||||
process.env.NEXT_PUBLIC_MINIO_URL ?? "http://localhost:9000"
|
||||
).replace(/\/$/, "");
|
||||
|
||||
/** Build a public object URL from a file's bucket + key. */
|
||||
export function publicFileUrl(bucket: string, key: string): string {
|
||||
return `${MINIO_PUBLIC_URL}/${bucket}/${key}`;
|
||||
}
|
||||
|
||||
export interface UploadedFile {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
mime_type?: string;
|
||||
}
|
||||
Reference in New Issue
Block a user