S3
This commit is contained in:
41
src/pages/api/auth.ts
Normal file
41
src/pages/api/auth.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import type { APIRoute } from "astro";
|
||||
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
try {
|
||||
const { code } = await request.json();
|
||||
const secretCode = process.env.SECRET_CODE || import.meta.env.SECRET_CODE;
|
||||
|
||||
if (!code || code !== secretCode) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: "Invalid code",
|
||||
}),
|
||||
{
|
||||
status: 401,
|
||||
headers,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
} catch (error) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: "Authentication failed",
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers,
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
148
src/pages/api/rsvp.ts
Normal file
148
src/pages/api/rsvp.ts
Normal file
@ -0,0 +1,148 @@
|
||||
import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
|
||||
import type { APIRoute } from "astro";
|
||||
|
||||
// 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 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 escaped = field.replace(/"/g, '""');
|
||||
return `"${escaped}"`;
|
||||
});
|
||||
csvRows.push(row.join(","));
|
||||
});
|
||||
|
||||
return csvRows.join("\n");
|
||||
};
|
||||
|
||||
// Helper function to parse CSV string to array of objects
|
||||
const csvToObjects = (csv: string): RSVPEntry[] => {
|
||||
const lines = csv.split("\n");
|
||||
const headers = lines[0].split(",").map(h => h.trim());
|
||||
|
||||
return lines
|
||||
.slice(1) // Skip headers
|
||||
.filter(line => line.trim()) // Skip empty lines
|
||||
.map(line => {
|
||||
const values = line.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g) || [];
|
||||
const entry: Partial<RSVPEntry> = {};
|
||||
|
||||
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;
|
||||
});
|
||||
|
||||
return entry as RSVPEntry;
|
||||
});
|
||||
};
|
||||
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
console.log("API endpoint hit - starting request processing");
|
||||
|
||||
const headers = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
try {
|
||||
const s3Host = process.env.S3_HOST || import.meta.env.S3_HOST;
|
||||
const endpoint = `https://${s3Host}`;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// Add new RSVP
|
||||
existingRsvps.push({
|
||||
...newRsvp,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error handling RSVP:", error);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
details: error instanceof Error ? error.stack : undefined,
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers,
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import RSVP from "../components/RSVP.tsx";
|
||||
import SignIn from "../components/SignIn.tsx";
|
||||
---
|
||||
|
||||
<Layout>
|
||||
@ -9,10 +10,32 @@ import RSVP from "../components/RSVP.tsx";
|
||||
Please RSVP using the form below:
|
||||
</div>
|
||||
|
||||
<RSVP client:load />
|
||||
<div id="auth-container">
|
||||
<SignIn client:load onSuccess={() => {}} />
|
||||
</div>
|
||||
|
||||
<div id="rsvp-container" class="hidden">
|
||||
<RSVP client:load />
|
||||
</div>
|
||||
|
||||
<div class="flex flex-row gap-2 justify-center items-center">
|
||||
<a class="btn btn-primary" href="/">Home</a>
|
||||
</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("rsvp-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("rsvp-container")?.classList.remove("hidden");
|
||||
});
|
||||
</script>
|
||||
|
Reference in New Issue
Block a user