Wonfidence
This commit is contained in:
@ -1,18 +1,25 @@
|
||||
import type { APIRoute } from "astro";
|
||||
|
||||
interface AuthRequest {
|
||||
code: string;
|
||||
requiredRole?: "guest" | "admin";
|
||||
}
|
||||
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
try {
|
||||
const { code } = await request.json();
|
||||
const { code, requiredRole = "guest" } = (await request.json()) as AuthRequest;
|
||||
const secretCode = process.env.SECRET_CODE || import.meta.env.SECRET_CODE;
|
||||
const adminCode = process.env.ADMIN_CODE || import.meta.env.ADMIN_CODE;
|
||||
|
||||
console.log("Received code:", code); // For debugging
|
||||
console.log("Secret code:", secretCode); // For debugging
|
||||
|
||||
if (!code || code !== secretCode) {
|
||||
let role = "guest";
|
||||
|
||||
if (code === adminCode) {
|
||||
role = "admin";
|
||||
} else if (code !== secretCode) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
@ -25,11 +32,25 @@ export const POST: APIRoute = async ({ request }) => {
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
if (requiredRole === "admin" && role !== "admin") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: "Admin access required",
|
||||
}),
|
||||
{
|
||||
status: 403,
|
||||
headers,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ success: true, role }), {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Authentication failed:", error);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
|
123
src/pages/api/registry/[id].ts
Normal file
123
src/pages/api/registry/[id].ts
Normal file
@ -0,0 +1,123 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { getS3Data, putS3Data } from "../../../lib/s3";
|
||||
import type { RegistryItem } from "../../../lib/types";
|
||||
|
||||
const REGISTRY_FILE_KEY = "baby-registry.json";
|
||||
|
||||
// GET: Get a specific registry item by ID
|
||||
export const GET: APIRoute = async ({ params }) => {
|
||||
try {
|
||||
const { id } = params;
|
||||
if (!id) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Item ID is required" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const registry = await getS3Data<RegistryItem[]>(REGISTRY_FILE_KEY) || [];
|
||||
const item = registry.find((item) => item.id === id);
|
||||
|
||||
if (!item) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Item not found" }),
|
||||
{ status: 404, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify(item), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("Error getting registry item:", error.message);
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Failed to get item" }),
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// PUT: Update an existing registry item
|
||||
export const PUT: APIRoute = async ({ request, params }) => {
|
||||
try {
|
||||
const { id } = params;
|
||||
if (!id) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Item ID is required" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, taken, link } = body;
|
||||
|
||||
const registry = await getS3Data<RegistryItem[]>(REGISTRY_FILE_KEY) || [];
|
||||
const itemIndex = registry.findIndex((item) => item.id === id);
|
||||
|
||||
if (itemIndex === -1) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Item not found" }),
|
||||
{ status: 404, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Update the item with the provided values
|
||||
registry[itemIndex] = {
|
||||
...registry[itemIndex],
|
||||
name: name !== undefined ? name : registry[itemIndex].name,
|
||||
taken: taken !== undefined ? taken : registry[itemIndex].taken,
|
||||
link: link !== undefined ? link : registry[itemIndex].link,
|
||||
};
|
||||
|
||||
await putS3Data(REGISTRY_FILE_KEY, registry);
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("Error updating registry item:", error.message);
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Failed to update item" }),
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// DELETE: Delete a registry item
|
||||
export const DELETE: APIRoute = async ({ params }) => {
|
||||
try {
|
||||
const { id } = params;
|
||||
if (!id) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Item ID is required" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const registry = await getS3Data<RegistryItem[]>(REGISTRY_FILE_KEY) || [];
|
||||
const itemIndex = registry.findIndex((item) => item.id === id);
|
||||
|
||||
if (itemIndex === -1) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Item not found" }),
|
||||
{ status: 404, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
registry.splice(itemIndex, 1); // Remove the item from the array
|
||||
await putS3Data(REGISTRY_FILE_KEY, registry);
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 204, // No Content
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("Error deleting registry item:", error.message);
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Failed to delete item" }),
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
};
|
60
src/pages/api/registry/index.ts
Normal file
60
src/pages/api/registry/index.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { getS3Data, putS3Data } from "../../../lib/s3";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import type { RegistryItem } from "../../../lib/types";
|
||||
|
||||
const REGISTRY_FILE_KEY = "baby-registry.json";
|
||||
|
||||
// GET: List all registry items
|
||||
export const GET: APIRoute = async () => {
|
||||
try {
|
||||
const registry = await getS3Data<RegistryItem[]>(REGISTRY_FILE_KEY) || [];
|
||||
return new Response(JSON.stringify(registry), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("Error listing registry items:", error.message);
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Failed to list items" }),
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// POST: Create a new registry item
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { name, link } = body;
|
||||
|
||||
if (!name) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Name is required" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const registry = await getS3Data<RegistryItem[]>(REGISTRY_FILE_KEY) || [];
|
||||
const newItem: RegistryItem = {
|
||||
id: uuidv4(),
|
||||
name,
|
||||
taken: false,
|
||||
link,
|
||||
};
|
||||
|
||||
registry.push(newItem);
|
||||
await putS3Data(REGISTRY_FILE_KEY, registry);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, itemId: newItem.id }),
|
||||
{ status: 201, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error("Error adding item to registry:", error.message);
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, error: "Failed to add item" }),
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
};
|
@ -1,24 +1,14 @@
|
||||
import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
|
||||
import type { APIRoute } from "astro";
|
||||
import { getS3Data, putS3Data } from "../../lib/s3";
|
||||
import type { RSVPItem } from "../../lib/types";
|
||||
|
||||
// Define the structure of our RSVP data
|
||||
interface RSVPEntry {
|
||||
name: string;
|
||||
dietaryRestrictions: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
// Helper function to convert array of objects to CSV string
|
||||
const objectsToCSV = (data: RSVPEntry[]): string => {
|
||||
// Define headers
|
||||
const objectsToCSV = (data: RSVPItem[]): string => {
|
||||
const headers = ["name", "dietaryRestrictions", "timestamp"];
|
||||
const csvRows = [headers.join(",")];
|
||||
|
||||
// Add data rows
|
||||
data.forEach((entry) => {
|
||||
const row = headers.map((header) => {
|
||||
// Escape commas and quotes in the content
|
||||
const field = String(entry[header as keyof RSVPEntry]);
|
||||
const field = String(entry[header as keyof RSVPItem]);
|
||||
const escaped = field.replace(/"/g, '""');
|
||||
return `"${escaped}"`;
|
||||
});
|
||||
@ -28,26 +18,24 @@ const objectsToCSV = (data: RSVPEntry[]): string => {
|
||||
return csvRows.join("\n");
|
||||
};
|
||||
|
||||
// Helper function to parse CSV string to array of objects
|
||||
const csvToObjects = (csv: string): RSVPEntry[] => {
|
||||
const csvToObjects = (csv: string): RSVPItem[] => {
|
||||
const lines = csv.split("\n");
|
||||
const headers = lines[0].split(",").map(h => h.trim());
|
||||
|
||||
const headers = lines[0].split(",").map((h) => h.trim());
|
||||
|
||||
return lines
|
||||
.slice(1) // Skip headers
|
||||
.filter(line => line.trim()) // Skip empty lines
|
||||
.map(line => {
|
||||
.slice(1)
|
||||
.filter((line) => line.trim())
|
||||
.map((line) => {
|
||||
const values = line.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g) || [];
|
||||
const entry: Partial<RSVPEntry> = {};
|
||||
|
||||
const entry: Partial<RSVPItem> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
let value = values[index] || "";
|
||||
// Remove quotes and unescape doubled quotes
|
||||
value = value.replace(/^"(.*)"$/, "$1").replace(/""/g, '"');
|
||||
entry[header as keyof RSVPEntry] = value;
|
||||
entry[header as keyof RSVPItem] = value;
|
||||
});
|
||||
|
||||
return entry as RSVPEntry;
|
||||
return entry as RSVPItem;
|
||||
});
|
||||
};
|
||||
|
||||
@ -60,54 +48,21 @@ export const POST: APIRoute = async ({ request }) => {
|
||||
};
|
||||
|
||||
try {
|
||||
const s3Host = process.env.S3_HOST || import.meta.env.S3_HOST;
|
||||
const endpoint = `https://${s3Host}`;
|
||||
const FILE_KEY = "rsvp.csv";
|
||||
|
||||
console.log("Creating S3 client with config:", {
|
||||
region: process.env.S3_REGION || import.meta.env.S3_REGION,
|
||||
endpoint,
|
||||
});
|
||||
|
||||
const s3Client = new S3Client({
|
||||
region: process.env.S3_REGION || import.meta.env.S3_REGION,
|
||||
endpoint,
|
||||
credentials: {
|
||||
accessKeyId: process.env.S3_ACCESS_KEY || import.meta.env.S3_ACCESS_KEY,
|
||||
secretAccessKey: process.env.S3_SECRET_KEY || import.meta.env.S3_SECRET_KEY,
|
||||
},
|
||||
forcePathStyle: true,
|
||||
});
|
||||
|
||||
const BUCKET_NAME = process.env.S3_BUCKET_NAME || import.meta.env.S3_BUCKET_NAME;
|
||||
const FILE_KEY = "rsvp.csv"; // Changed to CSV extension
|
||||
|
||||
console.log("Parsing request body");
|
||||
const newRsvp = await request.json();
|
||||
console.log("Received RSVP data:", newRsvp);
|
||||
|
||||
// Try to get existing RSVPs
|
||||
let existingRsvps: RSVPEntry[] = [];
|
||||
try {
|
||||
console.log("Attempting to fetch existing RSVPs");
|
||||
const getCommand = new GetObjectCommand({
|
||||
Bucket: BUCKET_NAME,
|
||||
Key: FILE_KEY,
|
||||
});
|
||||
|
||||
console.log("Sending GET request to S3");
|
||||
const response = await s3Client.send(getCommand);
|
||||
console.log("Received response from S3 GET");
|
||||
|
||||
const fileContent = await response.Body?.transformToString();
|
||||
if (fileContent) {
|
||||
existingRsvps = csvToObjects(fileContent);
|
||||
console.log("Existing RSVPs loaded:", existingRsvps.length);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("No existing RSVP file found or error:", error);
|
||||
let existingRsvps: RSVPItem[] = [];
|
||||
|
||||
console.log("Attempting to fetch existing RSVPs");
|
||||
const fileContent = await getS3Data<string>(FILE_KEY);
|
||||
if (fileContent) {
|
||||
existingRsvps = csvToObjects(fileContent);
|
||||
console.log("Existing RSVPs loaded:", existingRsvps.length);
|
||||
}
|
||||
|
||||
// Add new RSVP
|
||||
existingRsvps.push({
|
||||
...newRsvp,
|
||||
timestamp: new Date().toISOString(),
|
||||
@ -115,17 +70,8 @@ export const POST: APIRoute = async ({ request }) => {
|
||||
|
||||
console.log("Attempting to save updated RSVP list");
|
||||
const csvContent = objectsToCSV(existingRsvps);
|
||||
|
||||
const putCommand = new PutObjectCommand({
|
||||
Bucket: BUCKET_NAME,
|
||||
Key: FILE_KEY,
|
||||
Body: csvContent,
|
||||
ContentType: "text/csv",
|
||||
});
|
||||
|
||||
console.log("Sending PUT request to S3");
|
||||
await s3Client.send(putCommand);
|
||||
console.log("Successfully saved to S3");
|
||||
await putS3Data(FILE_KEY, csvContent, "text/csv");
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import SignOut from "../components/SignOut.tsx";
|
||||
---
|
||||
|
||||
<Layout>
|
||||
@ -7,7 +8,9 @@ import Layout from "../layouts/Layout.astro";
|
||||
<div class="text-center">❤️ Natasha + Ixabat ❤️</div>
|
||||
|
||||
<div class="flex flex-row gap-2 justify-center items-center">
|
||||
<a class="btn btn-primary" href="/rsvp">RSVP Now</a>
|
||||
<a class="btn btn-primary" href="/rsvp">RSVP</a>
|
||||
<a class="btn btn-primary" href="/registry">View Registry</a>
|
||||
<SignOut client:load />
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
|
55
src/pages/registry/admin.astro
Normal file
55
src/pages/registry/admin.astro
Normal file
@ -0,0 +1,55 @@
|
||||
---
|
||||
import Layout from "../../layouts/Layout.astro";
|
||||
import RegistryManager from "../../components/RegistryManager.tsx";
|
||||
import SignIn from "../../components/SignIn.tsx";
|
||||
import SignOut from "../../components/SignOut.tsx";
|
||||
---
|
||||
|
||||
<Layout title="Registry Manager">
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="text-center text-4xl">Registry Manager</div>
|
||||
|
||||
<div id="auth-container">
|
||||
<SignIn client:load onSuccess={() => {}} requiredRole="admin" />
|
||||
</div>
|
||||
|
||||
<div id="manager-container" class="hidden">
|
||||
<RegistryManager client:load />
|
||||
</div>
|
||||
|
||||
<div class="flex flex-row gap-2 justify-center items-center">
|
||||
<a class="btn btn-primary" href="/">Home</a>
|
||||
<SignOut client:load />
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
const checkAndUpdateVisibility = (role: string | null) => {
|
||||
if (role === "admin") {
|
||||
document.getElementById("auth-container")?.classList.add("hidden");
|
||||
document
|
||||
.getElementById("manager-container")
|
||||
?.classList.remove("hidden");
|
||||
} else {
|
||||
document
|
||||
.getElementById("auth-container")
|
||||
?.classList.remove("hidden");
|
||||
document
|
||||
.getElementById("manager-container")
|
||||
?.classList.add("hidden");
|
||||
}
|
||||
};
|
||||
|
||||
// Check auth state on page load
|
||||
const isAuthenticated =
|
||||
sessionStorage.getItem("isAuthenticated") === "true";
|
||||
const role = sessionStorage.getItem("role");
|
||||
checkAndUpdateVisibility(role);
|
||||
|
||||
// Add event listener for custom event from SignIn component
|
||||
document.addEventListener("auth-success", ((event: CustomEvent) => {
|
||||
const newRole = event.detail?.role || sessionStorage.getItem("role");
|
||||
checkAndUpdateVisibility(newRole);
|
||||
}) as EventListener);
|
||||
</script>
|
47
src/pages/registry/index.astro
Normal file
47
src/pages/registry/index.astro
Normal file
@ -0,0 +1,47 @@
|
||||
---
|
||||
import Layout from "../../layouts/Layout.astro";
|
||||
import RegistryList from "../../components/RegistryList.tsx";
|
||||
import SignIn from "../../components/SignIn.tsx";
|
||||
import SignOut from "../../components/SignOut.tsx";
|
||||
---
|
||||
|
||||
<Layout title="Baby Registry">
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="text-center text-4xl">
|
||||
View and Claim Items from the Baby Registry:
|
||||
</div>
|
||||
|
||||
<div id="auth-container">
|
||||
<SignIn client:load onSuccess={() => {}} requiredRole="guest" />
|
||||
</div>
|
||||
|
||||
<div id="registry-container" class="hidden">
|
||||
<RegistryList client:load />
|
||||
</div>
|
||||
|
||||
<div class="flex flex-row gap-2 justify-center items-center">
|
||||
<a class="btn btn-primary" href="/">Home</a>
|
||||
<SignOut client:load />
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
// Check auth state on page load
|
||||
const isAuthenticated =
|
||||
sessionStorage.getItem("isAuthenticated") === "true";
|
||||
if (isAuthenticated) {
|
||||
document.getElementById("auth-container")?.classList.add("hidden");
|
||||
document
|
||||
.getElementById("registry-container")
|
||||
?.classList.remove("hidden");
|
||||
}
|
||||
|
||||
// Add event listener for custom event from SignIn component
|
||||
document.addEventListener("auth-success", () => {
|
||||
document.getElementById("auth-container")?.classList.add("hidden");
|
||||
document
|
||||
.getElementById("registry-container")
|
||||
?.classList.remove("hidden");
|
||||
});
|
||||
</script>
|
@ -2,6 +2,7 @@
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import RSVP from "../components/RSVP.tsx";
|
||||
import SignIn from "../components/SignIn.tsx";
|
||||
import SignOut from "../components/SignOut.tsx";
|
||||
---
|
||||
|
||||
<Layout>
|
||||
@ -11,7 +12,7 @@ import SignIn from "../components/SignIn.tsx";
|
||||
</div>
|
||||
|
||||
<div id="auth-container">
|
||||
<SignIn client:load onSuccess={() => {}} />
|
||||
<SignIn client:load onSuccess={() => {}} requiredRole="guest" />
|
||||
</div>
|
||||
|
||||
<div id="rsvp-container" class="hidden">
|
||||
@ -20,6 +21,7 @@ import SignIn from "../components/SignIn.tsx";
|
||||
|
||||
<div class="flex flex-row gap-2 justify-center items-center">
|
||||
<a class="btn btn-primary" href="/">Home</a>
|
||||
<SignOut client:load />
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
|
Reference in New Issue
Block a user