Skip to content

Commit

Permalink
Merge pull request #130 from shreyas-omkar/prod
Browse files Browse the repository at this point in the history
Shifted All Frontend Validations To Backend
  • Loading branch information
SkySingh04 authored Dec 21, 2024
2 parents e4b9588 + 7846eca commit f973249
Show file tree
Hide file tree
Showing 12 changed files with 925 additions and 478 deletions.
92 changes: 64 additions & 28 deletions app/(default)/api/admin/route.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
import { db } from "@/Firebase";
import {
doc,
getDoc,
setDoc
getDoc,
setDoc,
} from "firebase/firestore";
import { NextResponse } from "next/server";
import { NextResponse } from "next/server";

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
const uid = searchParams.get("uid");

if (!uid) {
return NextResponse.json(
{ error: "UID is required" },
{ status: 400 }
);
}

const adminDocRef = doc(db, "admin", uid);
const adminDocSnap = await getDoc(adminDocRef);

if (!adminDocSnap.exists()) {
return NextResponse.json(
{ error: "User is not an admin" , isAdmin: false },
{ status: 403 }
{ error: "User is not an admin", isAdmin: false },
{ status: 403 }
);
}
else {
} else {
return NextResponse.json(
{ message: "User is an admin" , isAdmin: true },
{ status: 200 }
{ message: "User is an admin", isAdmin: true },
{ status: 200 }
);
}
} catch (error) {
Expand All @@ -49,23 +52,56 @@ export async function GET(request: Request) {
}

export async function POST(request: Request) {
const { email, role , userId} = await request.json();
try{await setDoc(doc(db, 'admin', userId), {
email,
role,
});}catch (error) {
if (error instanceof Error) {
console.error("Error details:", error.message);
return NextResponse.json(
{ error: "An error occurred", details: error.message },
{ status: 500 }
);
} else {
console.error("Unknown error:", error);
return NextResponse.json(
{ error: "An unknown error occurred" },
{ status: 500 }
);
}
}
const { email, role, userId } = await request.json();

// Validate required fields
if (!email || !role || !userId) {
return NextResponse.json(
{ error: "Email, role, and userId are required" },
{ status: 400 }
);
}

// Validate email format
if (!emailRegex.test(email)) {
return NextResponse.json(
{ error: "Invalid email format" },
{ status: 400 }
);
}

// Validate role (ensure it's one of the allowed roles, e.g., admin, user)
const allowedRoles = ['admin', 'user'];
if (!allowedRoles.includes(role)) {
return NextResponse.json(
{ error: `Invalid role. Allowed roles are: ${allowedRoles.join(', ')}` },
{ status: 400 }
);
}

try {
await setDoc(doc(db, 'admin', userId), {
email,
role,
});

return NextResponse.json(
{ message: "Admin data saved successfully" },
{ status: 200 }
);
} catch (error) {
if (error instanceof Error) {
console.error("Error details:", error.message);
return NextResponse.json(
{ error: "An error occurred", details: error.message },
{ status: 500 }
);
} else {
console.error("Unknown error:", error);
return NextResponse.json(
{ error: "An unknown error occurred" },
{ status: 500 }
);
}
}
}
122 changes: 90 additions & 32 deletions app/(default)/api/events/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,61 @@ import {
deleteDoc,
setDoc
} from "firebase/firestore";
import { NextResponse } from "next/server";
import { NextResponse } from "next/server";
import { v4 as uuidv4 } from 'uuid';

// Helper function to validate event data
const validateEvent = (event: any) => {
const errors: string[] = [];
const { eventName, eventDate, lastDateOfRegistration, description, imageURL, registrationLink } = event;

if (!eventName || typeof eventName !== "string" || eventName.trim().length === 0) {
errors.push("Event name is required and must be a non-empty string.");
}

if (!eventDate || isNaN(Date.parse(eventDate))) {
errors.push("Event date is required and must be a valid date.");
}

if (!lastDateOfRegistration || isNaN(Date.parse(lastDateOfRegistration))) {
errors.push("Last date of registration is required and must be a valid date.");
} else if (new Date(lastDateOfRegistration) > new Date(eventDate)) {
errors.push("Last date of registration must be before the event date.");
}

if (!description || typeof description !== "string" || description.trim().length < 10) {
errors.push("Description is required and must be at least 10 characters long.");
}

if (!imageURL || typeof imageURL !== "string" || !imageURL.startsWith("http")) {
errors.push("Image URL is required and must be a valid URL.");
}

if (!registrationLink || typeof registrationLink !== "string" || !registrationLink.startsWith("http")) {
errors.push("Registration link is required and must be a valid URL.");
}

return errors;
};

// GET request
export async function GET(request: Request) {
try {
const eventsCollection = collection(db, "events");
const eventSnapshot = await getDocs(eventsCollection);
const data = eventSnapshot.docs.map((doc) => doc.data());
const eventsList = data.map((event : any) => {
return {
id: event.id,
eventName: event.eventName,
description: event.description,
eventDate: event.eventDate,
lastDateOfRegistration: event.lastDateOfRegistration,
dateCreated: event.dateCreated,
dateModified: event.dateModified,
imageURL: event.imageURL,
registrationLink: event.registrationLink,
};
});
const eventSnapshot = await getDocs(eventsCollection);
const data = eventSnapshot.docs.map((doc) => doc.data());
const eventsList = data.map((event: any) => ({
id: event.id,
eventName: event.eventName,
description: event.description,
eventDate: event.eventDate,
lastDateOfRegistration: event.lastDateOfRegistration,
dateCreated: event.dateCreated,
dateModified: event.dateModified,
imageURL: event.imageURL,
registrationLink: event.registrationLink,
}));

return NextResponse.json({ events: eventsList }, { status: 200 });
} catch (error) {
if (error instanceof Error) {
Expand All @@ -47,15 +80,25 @@ export async function GET(request: Request) {
}
}

// POST request
export async function POST(request: Request) {
try {
const newEvent = await request.json();
const eventId = uuidv4();
const validationErrors = validateEvent(newEvent);

if (validationErrors.length > 0) {
return NextResponse.json(
{ error: "Validation failed", details: validationErrors },
{ status: 400 }
);
}

const eventId = uuidv4();
const currentDate = new Date().toISOString();
const { eventName, eventDate, lastDateOfRegistration, description, imageURL, registrationLink } = newEvent;
await setDoc( doc(db , "events" , eventId), {
id : eventId,

await setDoc(doc(db, "events", eventId), {
id: eventId,
eventName,
eventDate,
lastDateOfRegistration,
Expand All @@ -64,7 +107,8 @@ export async function POST(request: Request) {
registrationLink,
dateCreated: currentDate,
dateModified: currentDate,
});
});

return NextResponse.json({ id: eventId }, { status: 201 });
} catch (error) {
if (error instanceof Error) {
Expand All @@ -83,21 +127,36 @@ export async function POST(request: Request) {
}
}

// PUT request
export async function PUT(request: Request) {
try{
try {
const { searchParams } = new URL(request.url);
const eventid = searchParams.get("eventid");

if (!eventid) {
return NextResponse.json(
{ error: "Event ID is required" },
{ status: 400 }
);
}

const updatedEvent = await request.json();
await updateDoc(doc(db, "events", eventid), updatedEvent);
return NextResponse.json({ id: eventid }, { status: 200 });
const validationErrors = validateEvent(updatedEvent);

}catch (error) {
if (validationErrors.length > 0) {
return NextResponse.json(
{ error: "Validation failed", details: validationErrors },
{ status: 400 }
);
}

await updateDoc(doc(db, "events", eventid), {
...updatedEvent,
dateModified: new Date().toISOString(),
});

return NextResponse.json({ id: eventid }, { status: 200 });
} catch (error) {
if (error instanceof Error) {
console.error("Error details:", error.message);
return NextResponse.json(
Expand All @@ -114,19 +173,22 @@ export async function PUT(request: Request) {
}
}

// DELETE request
export async function DELETE(request: Request) {
try{
try {
const { searchParams } = new URL(request.url);
const eventid = searchParams.get("eventid");

if (!eventid) {
return NextResponse.json(
{ error: "Event ID is required" },
{ status: 400 }
);
}
await deleteDoc(doc(db, "events", eventid));
}
catch (error) {

await deleteDoc(doc(db, "events", eventid));
return NextResponse.json({ message: "Event deleted successfully" }, { status: 200 });
} catch (error) {
if (error instanceof Error) {
console.error("Error details:", error.message);
return NextResponse.json(
Expand All @@ -142,7 +204,3 @@ export async function DELETE(request: Request) {
}
}
}




Loading

0 comments on commit f973249

Please sign in to comment.