feat: upload images vers bucket Supabase privé avec Signed URLs
- Nouvelle route POST /api/admin/upload : upload multipart vers le bucket private-gallery, validation MIME + taille (max 5 Mo), retourne storage:path - lib/site-images.ts : détecte le préfixe "storage:" et génère une Signed URL temporaire (60 min) côté serveur avant chaque rendu de page - GET /api/admin/site-images : résout aussi les signed URLs pour les previews admin (champ previewUrl distinct de url brute) - PUT /api/admin/site-images : accepte désormais les chemins "storage:..." en plus des URLs externes - Page admin images : drag & drop + input file avec upload automatique + sauvegarde en BDD, badge "bucket privé", instructions SQL pour créer la table et la policy du bucket private-gallery https://claude.ai/code/session_01PzA98VhLMmsHpzs7gnLHGs
This commit is contained in:
@@ -1,60 +1,169 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
interface SiteImage {
|
interface SiteImage {
|
||||||
key: string;
|
key: string;
|
||||||
url: string;
|
url: string; // valeur brute (ex: "storage:hero_portrait/image.jpg" ou "https://...")
|
||||||
|
previewUrl: string; // URL résolvée pour l'affichage
|
||||||
label: string;
|
label: string;
|
||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type UploadState = "idle" | "uploading" | "saving" | "done" | "error";
|
||||||
|
|
||||||
|
interface ImageCardState {
|
||||||
|
editUrl: string; // valeur brute en cours d'édition
|
||||||
|
previewUrl: string; // URL pour l'aperçu
|
||||||
|
uploadState: UploadState;
|
||||||
|
uploadError: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export default function AdminImages() {
|
export default function AdminImages() {
|
||||||
const [images, setImages] = useState<SiteImage[]>([]);
|
const [images, setImages] = useState<SiteImage[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [saving, setSaving] = useState<string | null>(null);
|
const [cardState, setCardState] = useState<Record<string, ImageCardState>>({});
|
||||||
const [editUrls, setEditUrls] = useState<Record<string, string>>({});
|
const [globalMessage, setGlobalMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
|
||||||
const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
|
const [draggingOver, setDraggingOver] = useState<string | null>(null);
|
||||||
|
const fileInputRefs = useRef<Record<string, HTMLInputElement | null>>({});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch("/api/admin/site-images")
|
fetch("/api/admin/site-images")
|
||||||
.then((r) => r.json())
|
.then((r) => r.json())
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
setImages(data.images || []);
|
const imgs: SiteImage[] = data.images || [];
|
||||||
const urls: Record<string, string> = {};
|
setImages(imgs);
|
||||||
for (const img of data.images || []) {
|
const state: Record<string, ImageCardState> = {};
|
||||||
urls[img.key] = img.url;
|
for (const img of imgs) {
|
||||||
|
state[img.key] = {
|
||||||
|
editUrl: img.url,
|
||||||
|
previewUrl: img.previewUrl,
|
||||||
|
uploadState: "idle",
|
||||||
|
uploadError: null,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
setEditUrls(urls);
|
setCardState(state);
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleSave = async (key: string) => {
|
const updateCard = useCallback((key: string, patch: Partial<ImageCardState>) => {
|
||||||
setSaving(key);
|
setCardState((prev) => ({ ...prev, [key]: { ...prev[key], ...patch } }));
|
||||||
setMessage(null);
|
}, []);
|
||||||
|
|
||||||
|
// Upload d'un fichier + sauvegarde automatique
|
||||||
|
const handleFile = useCallback(
|
||||||
|
async (key: string, file: File) => {
|
||||||
|
updateCard(key, { uploadState: "uploading", uploadError: null });
|
||||||
|
|
||||||
|
// Aperçu local immédiat (object URL)
|
||||||
|
const localPreview = URL.createObjectURL(file);
|
||||||
|
updateCard(key, { previewUrl: localPreview });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append("file", file);
|
||||||
|
form.append("key", key);
|
||||||
|
|
||||||
|
const uploadRes = await fetch("/api/admin/upload", { method: "POST", body: form });
|
||||||
|
const uploadData = await uploadRes.json();
|
||||||
|
|
||||||
|
if (!uploadRes.ok) {
|
||||||
|
updateCard(key, { uploadState: "error", uploadError: uploadData.error || "Erreur upload" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { storagePath } = uploadData as { storagePath: string };
|
||||||
|
|
||||||
|
// Sauvegarde automatique en BDD
|
||||||
|
updateCard(key, { uploadState: "saving" });
|
||||||
|
const saveRes = await fetch("/api/admin/site-images", {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ key, url: storagePath }),
|
||||||
|
});
|
||||||
|
const saveData = await saveRes.json();
|
||||||
|
|
||||||
|
if (!saveRes.ok) {
|
||||||
|
updateCard(key, { uploadState: "error", uploadError: saveData.error || "Erreur sauvegarde" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Succès : mettre à jour l'état
|
||||||
|
updateCard(key, { editUrl: storagePath, uploadState: "done", uploadError: null });
|
||||||
|
setImages((prev) =>
|
||||||
|
prev.map((img) =>
|
||||||
|
img.key === key
|
||||||
|
? { ...img, url: storagePath, previewUrl: localPreview, updated_at: new Date().toISOString() }
|
||||||
|
: img
|
||||||
|
)
|
||||||
|
);
|
||||||
|
setGlobalMessage({ type: "success", text: `"${key}" uploadé et sauvegardé !` });
|
||||||
|
setTimeout(() => updateCard(key, { uploadState: "idle" }), 3000);
|
||||||
|
} catch {
|
||||||
|
updateCard(key, { uploadState: "error", uploadError: "Erreur réseau" });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[updateCard]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Sauvegarde manuelle d'une URL externe
|
||||||
|
const handleSaveUrl = useCallback(
|
||||||
|
async (key: string) => {
|
||||||
|
const url = cardState[key]?.editUrl;
|
||||||
|
if (!url) return;
|
||||||
|
|
||||||
|
updateCard(key, { uploadState: "saving", uploadError: null });
|
||||||
|
setGlobalMessage(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/site-images", {
|
const res = await fetch("/api/admin/site-images", {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ key, url: editUrls[key] }),
|
body: JSON.stringify({ key, url }),
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
setMessage({ type: "success", text: `Image "${key}" mise à jour !` });
|
updateCard(key, { previewUrl: url, uploadState: "done" });
|
||||||
setImages((prev) =>
|
setImages((prev) =>
|
||||||
prev.map((img) =>
|
prev.map((img) =>
|
||||||
img.key === key ? { ...img, url: editUrls[key], updated_at: new Date().toISOString() } : img
|
img.key === key
|
||||||
|
? { ...img, url, previewUrl: url, updated_at: new Date().toISOString() }
|
||||||
|
: img
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
setGlobalMessage({ type: "success", text: `"${key}" mis à jour !` });
|
||||||
|
setTimeout(() => updateCard(key, { uploadState: "idle" }), 3000);
|
||||||
} else {
|
} else {
|
||||||
setMessage({ type: "error", text: data.error || "Erreur" });
|
updateCard(key, { uploadState: "error", uploadError: data.error || "Erreur" });
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
setMessage({ type: "error", text: "Erreur réseau" });
|
updateCard(key, { uploadState: "error", uploadError: "Erreur réseau" });
|
||||||
}
|
}
|
||||||
setSaving(null);
|
},
|
||||||
};
|
[cardState, updateCard]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleDrop = useCallback(
|
||||||
|
(key: string, e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDraggingOver(null);
|
||||||
|
const file = e.dataTransfer.files[0];
|
||||||
|
if (file) handleFile(key, file);
|
||||||
|
},
|
||||||
|
[handleFile]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleFileInputChange = useCallback(
|
||||||
|
(key: string, e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (file) handleFile(key, file);
|
||||||
|
// Reset input pour permettre de re-sélectionner le même fichier
|
||||||
|
e.target.value = "";
|
||||||
|
},
|
||||||
|
[handleFile]
|
||||||
|
);
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
@@ -70,24 +179,25 @@ export default function AdminImages() {
|
|||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
<h1 className="text-3xl font-bold text-white mb-2">Images du site</h1>
|
<h1 className="text-3xl font-bold text-white mb-2">Images du site</h1>
|
||||||
<p className="text-white/60">
|
<p className="text-white/60">
|
||||||
Changez les URLs des images affichées sur le site. Collez un lien Noelshack, Unsplash, ou tout autre hébergeur d'images.
|
Uploadez vos fichiers directement dans le bucket privé Supabase, ou collez une URL externe.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{message && (
|
{globalMessage && (
|
||||||
<div
|
<div
|
||||||
className={`mb-6 p-4 rounded-xl text-sm font-medium ${
|
className={`mb-6 p-4 rounded-xl text-sm font-medium ${
|
||||||
message.type === "success" ? "bg-success/10 text-success" : "bg-red-500/10 text-red-400"
|
globalMessage.type === "success" ? "bg-success/10 text-success" : "bg-red-500/10 text-red-400"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{message.text}
|
{globalMessage.text}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Info SQL */}
|
{/* Info SQL */}
|
||||||
<div className="mb-8 bg-dark-light border border-dark-border rounded-[20px] p-6">
|
<div className="mb-8 bg-dark-light border border-dark-border rounded-[20px] p-6 space-y-4">
|
||||||
|
<div>
|
||||||
<p className="text-white/50 text-xs mb-2 font-medium">
|
<p className="text-white/50 text-xs mb-2 font-medium">
|
||||||
Si la sauvegarde échoue, créez la table dans Supabase (SQL Editor) :
|
1. Créer la table <code className="text-orange">site_images</code> dans Supabase (SQL Editor) :
|
||||||
</p>
|
</p>
|
||||||
<pre className="bg-black/30 rounded-lg p-3 text-xs text-green-400 overflow-x-auto">
|
<pre className="bg-black/30 rounded-lg p-3 text-xs text-green-400 overflow-x-auto">
|
||||||
{`CREATE TABLE site_images (
|
{`CREATE TABLE site_images (
|
||||||
@@ -98,16 +208,41 @@ export default function AdminImages() {
|
|||||||
);`}
|
);`}
|
||||||
</pre>
|
</pre>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-white/50 text-xs mb-2 font-medium">
|
||||||
|
2. Créer le bucket <code className="text-orange">private-gallery</code> (Storage → New bucket, décocher "Public") puis appliquer cette policy :
|
||||||
|
</p>
|
||||||
|
<pre className="bg-black/30 rounded-lg p-3 text-xs text-green-400 overflow-x-auto">
|
||||||
|
{`-- Autoriser le service role à tout faire (uploads serveur)
|
||||||
|
CREATE POLICY "service_role_full_access"
|
||||||
|
ON storage.objects FOR ALL
|
||||||
|
TO service_role
|
||||||
|
USING (bucket_id = 'private-gallery')
|
||||||
|
WITH CHECK (bucket_id = 'private-gallery');`}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{images.map((img) => (
|
{images.map((img) => {
|
||||||
|
const state = cardState[img.key];
|
||||||
|
if (!state) return null;
|
||||||
|
const isUploading = state.uploadState === "uploading";
|
||||||
|
const isSaving = state.uploadState === "saving";
|
||||||
|
const isBusy = isUploading || isSaving;
|
||||||
|
const isDone = state.uploadState === "done";
|
||||||
|
const isError = state.uploadState === "error";
|
||||||
|
const isStoredInBucket = state.editUrl.startsWith("storage:");
|
||||||
|
const urlChanged = state.editUrl !== img.url;
|
||||||
|
|
||||||
|
return (
|
||||||
<div key={img.key} className="bg-dark-light border border-dark-border rounded-[20px] p-6">
|
<div key={img.key} className="bg-dark-light border border-dark-border rounded-[20px] p-6">
|
||||||
<div className="flex items-start gap-6">
|
<div className="flex items-start gap-6">
|
||||||
{/* Preview */}
|
{/* Preview */}
|
||||||
<div className="w-32 h-24 rounded-xl overflow-hidden bg-black/30 shrink-0">
|
<div className="w-32 h-24 rounded-xl overflow-hidden bg-black/30 shrink-0">
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img
|
<img
|
||||||
src={editUrls[img.key] || img.url}
|
src={state.previewUrl}
|
||||||
alt={img.label}
|
alt={img.label}
|
||||||
className="w-full h-full object-cover"
|
className="w-full h-full object-cover"
|
||||||
onError={(e) => {
|
onError={(e) => {
|
||||||
@@ -117,12 +252,18 @@ export default function AdminImages() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Form */}
|
{/* Contenu */}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2 mb-1">
|
<div className="flex items-center gap-2 mb-1">
|
||||||
<h3 className="text-white font-semibold text-sm">{img.label}</h3>
|
<h3 className="text-white font-semibold text-sm">{img.label}</h3>
|
||||||
<span className="text-white/20 text-xs font-mono">{img.key}</span>
|
<span className="text-white/20 text-xs font-mono">{img.key}</span>
|
||||||
|
{isStoredInBucket && (
|
||||||
|
<span className="text-xs bg-orange/10 text-orange border border-orange/20 rounded-full px-2 py-0.5">
|
||||||
|
bucket privé
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{img.updated_at && (
|
{img.updated_at && (
|
||||||
<p className="text-white/30 text-xs mb-3">
|
<p className="text-white/30 text-xs mb-3">
|
||||||
Modifié le{" "}
|
Modifié le{" "}
|
||||||
@@ -135,26 +276,81 @@ export default function AdminImages() {
|
|||||||
})}
|
})}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Zone drag & drop */}
|
||||||
|
<div
|
||||||
|
className={`mb-3 border-2 border-dashed rounded-xl p-4 text-center transition-colors cursor-pointer ${
|
||||||
|
draggingOver === img.key
|
||||||
|
? "border-orange bg-orange/5"
|
||||||
|
: "border-dark-border hover:border-orange/40 hover:bg-white/2"
|
||||||
|
} ${isBusy ? "opacity-50 pointer-events-none" : ""}`}
|
||||||
|
onDragOver={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDraggingOver(img.key);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDraggingOver(null)}
|
||||||
|
onDrop={(e) => handleDrop(img.key, e)}
|
||||||
|
onClick={() => fileInputRefs.current[img.key]?.click()}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/webp,image/gif,image/avif"
|
||||||
|
className="hidden"
|
||||||
|
ref={(el) => { fileInputRefs.current[img.key] = el; }}
|
||||||
|
onChange={(e) => handleFileInputChange(img.key, e)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{isUploading ? (
|
||||||
|
<p className="text-orange text-xs font-medium">Upload en cours...</p>
|
||||||
|
) : isSaving ? (
|
||||||
|
<p className="text-orange text-xs font-medium">Sauvegarde...</p>
|
||||||
|
) : isDone ? (
|
||||||
|
<p className="text-success text-xs font-medium">Fichier enregistré !</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-white/50 text-xs">
|
||||||
|
<span className="text-white/80 font-medium">Glissez une image</span> ou{" "}
|
||||||
|
<span className="text-orange font-medium underline">parcourir</span>
|
||||||
|
</p>
|
||||||
|
<p className="text-white/25 text-xs">JPEG · PNG · WebP · GIF · AVIF — max 5 Mo</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isError && (
|
||||||
|
<p className="text-red-400 text-xs mb-2">{state.uploadError}</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* URL externe (fallback) */}
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<input
|
<input
|
||||||
type="url"
|
type="url"
|
||||||
value={editUrls[img.key] || ""}
|
value={state.editUrl.startsWith("storage:") ? "" : state.editUrl}
|
||||||
onChange={(e) => setEditUrls((prev) => ({ ...prev, [img.key]: e.target.value }))}
|
onChange={(e) =>
|
||||||
placeholder="https://..."
|
updateCard(img.key, { editUrl: e.target.value, previewUrl: e.target.value })
|
||||||
className="flex-1 px-4 py-2.5 bg-black/30 border border-dark-border rounded-xl text-white text-sm placeholder:text-white/20 focus:border-orange focus:ring-1 focus:ring-orange outline-none"
|
}
|
||||||
|
placeholder="Ou coller une URL externe (https://...)"
|
||||||
|
disabled={isBusy}
|
||||||
|
className="flex-1 px-4 py-2.5 bg-black/30 border border-dark-border rounded-xl text-white text-sm placeholder:text-white/20 focus:border-orange focus:ring-1 focus:ring-orange outline-none disabled:opacity-40"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
onClick={() => handleSave(img.key)}
|
onClick={() => handleSaveUrl(img.key)}
|
||||||
disabled={saving === img.key || editUrls[img.key] === img.url}
|
disabled={
|
||||||
|
isBusy ||
|
||||||
|
!state.editUrl ||
|
||||||
|
state.editUrl.startsWith("storage:") ||
|
||||||
|
!urlChanged
|
||||||
|
}
|
||||||
className="px-5 py-2.5 bg-orange hover:bg-orange/90 disabled:opacity-30 text-white font-semibold text-sm rounded-xl transition-colors cursor-pointer disabled:cursor-not-allowed shrink-0"
|
className="px-5 py-2.5 bg-orange hover:bg-orange/90 disabled:opacity-30 text-white font-semibold text-sm rounded-xl transition-colors cursor-pointer disabled:cursor-not-allowed shrink-0"
|
||||||
>
|
>
|
||||||
{saving === img.key ? "..." : "Sauver"}
|
{isSaving ? "..." : "Sauver"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ interface SiteImageRow {
|
|||||||
updated_at: string;
|
updated_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const BUCKET = "private-gallery";
|
||||||
|
const SIGNED_URL_TTL = 3600; // 1 heure
|
||||||
|
|
||||||
async function checkAdmin() {
|
async function checkAdmin() {
|
||||||
const supabase = await createClient();
|
const supabase = await createClient();
|
||||||
const {
|
const {
|
||||||
@@ -27,6 +30,21 @@ async function checkAdmin() {
|
|||||||
return (profile as Pick<Profile, "is_admin"> | null)?.is_admin === true;
|
return (profile as Pick<Profile, "is_admin"> | null)?.is_admin === true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Génère une URL de prévisualisation pour l'admin.
|
||||||
|
* Pour les chemins "storage:", crée une Signed URL temporaire.
|
||||||
|
* Pour les URLs externes, retourne l'URL telle quelle.
|
||||||
|
*/
|
||||||
|
async function resolvePreviewUrl(rawUrl: string): Promise<string> {
|
||||||
|
if (!rawUrl.startsWith("storage:")) return rawUrl;
|
||||||
|
const filePath = rawUrl.slice("storage:".length);
|
||||||
|
const adminClient = createAdminClient();
|
||||||
|
const { data } = await adminClient.storage
|
||||||
|
.from(BUCKET)
|
||||||
|
.createSignedUrl(filePath, SIGNED_URL_TTL);
|
||||||
|
return data?.signedUrl ?? rawUrl;
|
||||||
|
}
|
||||||
|
|
||||||
// GET - Récupérer toutes les images
|
// GET - Récupérer toutes les images
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const isAdmin = await checkAdmin();
|
const isAdmin = await checkAdmin();
|
||||||
@@ -35,20 +53,25 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const supabase = createAdminClient();
|
const adminClient = createAdminClient();
|
||||||
const { data } = await supabase.from("site_images").select("*");
|
const { data } = await adminClient.from("site_images").select("*");
|
||||||
const rows = (data ?? []) as unknown as SiteImageRow[];
|
const rows = (data ?? []) as unknown as SiteImageRow[];
|
||||||
|
|
||||||
// Merge defaults avec les valeurs en base
|
// Merge defaults avec les valeurs en base, résoudre les signed URLs en parallèle
|
||||||
const images = Object.entries(DEFAULT_IMAGES).map(([key, def]) => {
|
const images = await Promise.all(
|
||||||
|
Object.entries(DEFAULT_IMAGES).map(async ([key, def]) => {
|
||||||
const saved = rows.find((d) => d.key === key);
|
const saved = rows.find((d) => d.key === key);
|
||||||
|
const rawUrl = saved?.url || def.url;
|
||||||
|
const previewUrl = await resolvePreviewUrl(rawUrl);
|
||||||
return {
|
return {
|
||||||
key,
|
key,
|
||||||
url: saved?.url || def.url,
|
url: rawUrl, // valeur brute stockée (ex: "storage:hero_portrait/image.jpg")
|
||||||
|
previewUrl, // URL résolvée pour l'affichage dans le navigateur
|
||||||
label: def.label,
|
label: def.label,
|
||||||
updated_at: saved?.updated_at || null,
|
updated_at: saved?.updated_at || null,
|
||||||
};
|
};
|
||||||
});
|
})
|
||||||
|
);
|
||||||
|
|
||||||
return NextResponse.json({ images });
|
return NextResponse.json({ images });
|
||||||
} catch {
|
} catch {
|
||||||
@@ -56,6 +79,7 @@ export async function GET() {
|
|||||||
const images = Object.entries(DEFAULT_IMAGES).map(([key, def]) => ({
|
const images = Object.entries(DEFAULT_IMAGES).map(([key, def]) => ({
|
||||||
key,
|
key,
|
||||||
url: def.url,
|
url: def.url,
|
||||||
|
previewUrl: def.url,
|
||||||
label: def.label,
|
label: def.label,
|
||||||
updated_at: null,
|
updated_at: null,
|
||||||
}));
|
}));
|
||||||
@@ -77,12 +101,15 @@ export async function PUT(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: "key et url requis" }, { status: 400 });
|
return NextResponse.json({ error: "key et url requis" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vérifier que l'URL est valide
|
// Accepter soit une URL externe (https://...) soit un chemin storage (storage:...)
|
||||||
|
const isStoragePath = url.startsWith("storage:");
|
||||||
|
if (!isStoragePath) {
|
||||||
try {
|
try {
|
||||||
new URL(url);
|
new URL(url);
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json({ error: "URL invalide" }, { status: 400 });
|
return NextResponse.json({ error: "URL invalide" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const success = await updateSiteImage(key, url);
|
const success = await updateSiteImage(key, url);
|
||||||
if (!success) {
|
if (!success) {
|
||||||
|
|||||||
85
app/api/admin/upload/route.ts
Normal file
85
app/api/admin/upload/route.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { createClient, createAdminClient } from "@/lib/supabase/server";
|
||||||
|
import type { Profile } from "@/types/database.types";
|
||||||
|
|
||||||
|
const BUCKET = "private-gallery";
|
||||||
|
|
||||||
|
async function checkAdmin() {
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) return false;
|
||||||
|
|
||||||
|
const adminClient = createAdminClient();
|
||||||
|
const { data: profile } = await adminClient
|
||||||
|
.from("profiles")
|
||||||
|
.select("is_admin")
|
||||||
|
.eq("id", user.id)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
return (profile as Pick<Profile, "is_admin"> | null)?.is_admin === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST - Upload un fichier dans le bucket private-gallery
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
const isAdmin = await checkAdmin();
|
||||||
|
if (!isAdmin) {
|
||||||
|
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let formData: FormData;
|
||||||
|
try {
|
||||||
|
formData = await request.formData();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "Corps de requête invalide" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = formData.get("file") as File | null;
|
||||||
|
const imageKey = formData.get("key") as string | null;
|
||||||
|
|
||||||
|
if (!file || !imageKey) {
|
||||||
|
return NextResponse.json({ error: "Champs 'file' et 'key' requis" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valider le type MIME
|
||||||
|
const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"];
|
||||||
|
if (!allowedTypes.includes(file.type)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Type de fichier non supporté. Utilisez JPEG, PNG, WebP, GIF ou AVIF." },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limiter à 5 Mo
|
||||||
|
if (file.size > 5 * 1024 * 1024) {
|
||||||
|
return NextResponse.json({ error: "Fichier trop volumineux (max 5 Mo)" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Construire le chemin : ex. "hero/image.jpg"
|
||||||
|
const ext = file.name.split(".").pop() ?? "jpg";
|
||||||
|
const sanitizedKey = imageKey.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||||
|
const filePath = `${sanitizedKey}/image.${ext}`;
|
||||||
|
|
||||||
|
const arrayBuffer = await file.arrayBuffer();
|
||||||
|
const buffer = new Uint8Array(arrayBuffer);
|
||||||
|
|
||||||
|
const adminClient = createAdminClient();
|
||||||
|
const { error } = await adminClient.storage
|
||||||
|
.from(BUCKET)
|
||||||
|
.upload(filePath, buffer, {
|
||||||
|
contentType: file.type,
|
||||||
|
upsert: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Erreur upload Supabase : ${error.message}` },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retourner le chemin avec préfixe "storage:"
|
||||||
|
const storagePath = `storage:${filePath}`;
|
||||||
|
return NextResponse.json({ storagePath, filePath });
|
||||||
|
}
|
||||||
@@ -43,8 +43,36 @@ export const DEFAULT_IMAGES: Record<string, { url: string; label: string }> = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const STORAGE_PREFIX = "storage:";
|
||||||
|
const BUCKET = "private-gallery";
|
||||||
|
// Durée de validité des Signed URLs : 1 heure
|
||||||
|
const SIGNED_URL_TTL = 3600;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout une valeur stockée en BDD vers une URL publique.
|
||||||
|
* Si la valeur commence par "storage:", génère une Signed URL temporaire (60 min)
|
||||||
|
* depuis le bucket privé Supabase.
|
||||||
|
* Sinon, retourne la valeur telle quelle (URL externe).
|
||||||
|
*/
|
||||||
|
async function resolveUrl(raw: string): Promise<string> {
|
||||||
|
if (!raw.startsWith(STORAGE_PREFIX)) return raw;
|
||||||
|
|
||||||
|
const filePath = raw.slice(STORAGE_PREFIX.length); // ex: "hero_portrait/image.jpg"
|
||||||
|
const supabase = createAdminClient();
|
||||||
|
const { data, error } = await supabase.storage
|
||||||
|
.from(BUCKET)
|
||||||
|
.createSignedUrl(filePath, SIGNED_URL_TTL);
|
||||||
|
|
||||||
|
if (error || !data?.signedUrl) {
|
||||||
|
// En cas d'erreur, on renvoie l'URL brute (le placeholder s'affichera)
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
return data.signedUrl;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Récupère toutes les images du site depuis Supabase.
|
* Récupère toutes les images du site depuis Supabase.
|
||||||
|
* Les valeurs "storage:..." sont converties en Signed URLs à la volée.
|
||||||
* Fallback sur les valeurs par défaut si la table n'existe pas.
|
* Fallback sur les valeurs par défaut si la table n'existe pas.
|
||||||
*/
|
*/
|
||||||
export async function getSiteImages(): Promise<Record<string, string>> {
|
export async function getSiteImages(): Promise<Record<string, string>> {
|
||||||
@@ -61,11 +89,14 @@ export async function getSiteImages(): Promise<Record<string, string>> {
|
|||||||
const rows = (data ?? []) as unknown as Pick<SiteImage, "key" | "url">[];
|
const rows = (data ?? []) as unknown as Pick<SiteImage, "key" | "url">[];
|
||||||
|
|
||||||
if (!error) {
|
if (!error) {
|
||||||
for (const row of rows) {
|
// Résoudre toutes les URLs en parallèle (signed URLs pour les paths storage:)
|
||||||
|
await Promise.all(
|
||||||
|
rows.map(async (row) => {
|
||||||
if (row.url) {
|
if (row.url) {
|
||||||
result[row.key] = row.url;
|
result[row.key] = await resolveUrl(row.url);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Table n'existe pas encore, on utilise les defaults
|
// Table n'existe pas encore, on utilise les defaults
|
||||||
@@ -76,6 +107,7 @@ export async function getSiteImages(): Promise<Record<string, string>> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Met à jour une image du site.
|
* Met à jour une image du site.
|
||||||
|
* Accepte une URL externe (https://...) ou un chemin storage (storage:...).
|
||||||
*/
|
*/
|
||||||
export async function updateSiteImage(key: string, url: string): Promise<boolean> {
|
export async function updateSiteImage(key: string, url: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
|
|||||||
Reference in New Issue
Block a user