diff --git a/api/reviews.js b/api/reviews.js index 07018e0..e66a413 100644 --- a/api/reviews.js +++ b/api/reviews.js @@ -5,8 +5,8 @@ * * Features: * - Real-time persistent feedback list storage via secure backend proxy - * - Eliminates client-side race conditions, CORS blocks, and overwrites - * - Multi-user chronological review preservation (new reviews unshift, existing updates) + * - Multi-user chronological review preservation + * - Strict Owner-Only Edit & Delete (Each user can only modify/delete their own review) * - Automated notification dispatch to Er. Adam Eehan */ @@ -65,7 +65,7 @@ async function saveToBin(feedbacks) { export default async function handler(req, res) { // CORS & No-Cache Headers res.setHeader("Access-Control-Allow-Origin", "*"); - res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type"); res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"); @@ -91,10 +91,52 @@ export default async function handler(req, res) { } } - // --- POST: Add new review or update existing review without deleting others --- + // --- DELETE (or POST action === 'delete'): Owner-Only Delete --- + const body = req.body || {}; + const query = req.query || {}; + const action = body.action || query.action; + + if (req.method === "DELETE" || action === "delete") { + try { + const targetId = body.id || query.id; + const userEmail = body.email || query.email; + + if (!targetId || !userEmail) { + return res.status(400).json({ success: false, error: "Review ID and authenticated user email are required." }); + } + + const cleanEmail = userEmail.trim().toLowerCase(); + const currentFeedbacks = await fetchLatestFromBin(); + const existing = currentFeedbacks.find(r => r.id === targetId || (r.email && r.email.toLowerCase() === cleanEmail)); + + if (!existing) { + return res.status(404).json({ success: false, error: "Review not found in database." }); + } + + // Security check: Only the owner can delete their review + if (!existing.email || existing.email.toLowerCase() !== cleanEmail) { + return res.status(403).json({ success: false, error: "Unauthorized: You can only delete your own review." }); + } + + const updatedFeedbacks = currentFeedbacks.filter(r => r.id !== existing.id); + await saveToBin(updatedFeedbacks); + + return res.status(200).json({ + success: true, + message: "Your review was successfully deleted.", + count: updatedFeedbacks.length, + reviews: updatedFeedbacks + }); + } catch (err) { + console.error("[Reviews API] Delete error:", err); + return res.status(500).json({ success: false, error: "Failed to delete review: " + err.message }); + } + } + + // --- POST: Add new review or edit existing review --- if (req.method === "POST") { try { - const { name, email, photo, rating, tag, text, id, date } = req.body || {}; + const { name, email, photo, rating, tag, text, id, date, isEdit } = body; if (!text || !text.trim()) { return res.status(400).json({ success: false, error: "Review text is required." }); @@ -102,41 +144,64 @@ export default async function handler(req, res) { const cleanName = (name && name.trim()) ? name.trim() : "Verified Member"; const cleanEmail = (email && email.trim()) ? email.trim().toLowerCase() : ""; + if (!cleanEmail) { + return res.status(400).json({ success: false, error: "Authenticated user email is required." }); + } + const cleanText = text.trim().slice(0, 1500); const cleanRating = (typeof rating === "number" && rating >= 1 && rating <= 5) ? rating : 5; const cleanTag = (tag && tag.trim()) ? tag.trim() : "Client / Collaborator"; const cleanPhoto = (photo && photo.trim()) ? photo.trim() : `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(cleanName)}`; - const cleanDate = date || new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }); - const reviewId = id || ("rev_" + Date.now()); - - const newReview = { - id: reviewId, - name: cleanName, - email: cleanEmail, - photo: cleanPhoto, - rating: cleanRating, - tag: cleanTag, - text: cleanText, - date: cleanDate - }; + const baseDate = date || new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }); + const cleanDate = isEdit ? `${baseDate.replace(" (Edited)", "")} (Edited)` : baseDate; // 1. Fetch current list of reviews from cloud const currentFeedbacks = await fetchLatestFromBin(); - - // 2. Check if this user (by email) already submitted a review let updatedFeedbacks = [...currentFeedbacks]; + + // 2. Locate existing review if editing or if user already reviewed let existingIndex = -1; - - if (cleanEmail) { + if (id) { + existingIndex = updatedFeedbacks.findIndex(r => r.id === id); + } + if (existingIndex === -1 && cleanEmail) { existingIndex = updatedFeedbacks.findIndex(r => r.email && r.email.toLowerCase() === cleanEmail); } + let reviewId = id || ("rev_" + Date.now()); + if (existingIndex >= 0) { - // User is updating their existing review -> Move updated review to top + const existingReview = updatedFeedbacks[existingIndex]; + // Security check: Only the owner can edit their review + if (existingReview.email && existingReview.email.toLowerCase() !== cleanEmail) { + return res.status(403).json({ success: false, error: "Unauthorized: You can only edit your own review." }); + } + reviewId = existingReview.id; + const updatedReview = { + id: reviewId, + name: cleanName, + email: cleanEmail, + photo: cleanPhoto, + rating: cleanRating, + tag: cleanTag, + text: cleanText, + date: cleanDate + }; + // Replace in place or move to top updatedFeedbacks.splice(existingIndex, 1); - updatedFeedbacks.unshift(newReview); + updatedFeedbacks.unshift(updatedReview); } else { - // New user -> Prepend to the list so older reviews are preserved! + // New review + const newReview = { + id: reviewId, + name: cleanName, + email: cleanEmail, + photo: cleanPhoto, + rating: cleanRating, + tag: cleanTag, + text: cleanText, + date: cleanDate + }; updatedFeedbacks.unshift(newReview); } @@ -149,23 +214,22 @@ export default async function handler(req, res) { method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({ - _subject: `🌟 New Real Feedback: ${cleanName} (${cleanRating} Stars) - airaaigroup.in`, + _subject: `🌟 ${existingIndex >= 0 ? "Review Edited" : "New Feedback"}: ${cleanName} (${cleanRating} Stars) - airaaigroup.in`, Name: cleanName, Email: cleanEmail, Rating: `${cleanRating} / 5 Stars`, Category: cleanTag, Review: cleanText, Date: cleanDate, + IsEdited: existingIndex >= 0, TotalReviewsInDatabase: updatedFeedbacks.length }) }).catch(() => {}); - } catch (mailErr) { - // ignore background mail errors - } + } catch (mailErr) {} return res.status(200).json({ success: true, - message: "Review successfully published and preserved in cloud database.", + message: existingIndex >= 0 ? "Review successfully updated." : "Review successfully published and preserved.", count: updatedFeedbacks.length, reviews: updatedFeedbacks }); @@ -179,5 +243,5 @@ export default async function handler(req, res) { } } - return res.status(405).json({ error: "Method not allowed. Use GET or POST." }); + return res.status(405).json({ error: "Method not allowed. Use GET, POST, or DELETE." }); } diff --git a/index.html b/index.html index 56dd184..27cdd15 100644 --- a/index.html +++ b/index.html @@ -1264,6 +1264,20 @@