Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/pbdsce/pbwebsite
Browse files Browse the repository at this point in the history
  • Loading branch information
SkySingh04 committed Aug 22, 2024
2 parents a7ba891 + d1f4bc4 commit 6285987
Show file tree
Hide file tree
Showing 11 changed files with 300 additions and 346 deletions.
49 changes: 31 additions & 18 deletions app/(default)/api/registration/recruitment/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,48 @@ import { addDoc, collection, getDocs } from "firebase/firestore";
import { NextResponse } from "next/server";

// Verify reCAPTCHA Token
async function verifyRecaptcha(token: string) {
const secretKey = process.env.RECAPTCHA_SECRET_KEY;
const response = await fetch(
`https://www.google.com/recaptcha/api/siteverify`,
{
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
secret: secretKey || "",
response: token,
}),
}
);
const data = await response.json();
return data.success;
}

// Add a new registration
export async function POST(request: Request) {
const formData = await request.json();
const { recaptcha_token, ...data } = formData;
const recaptchaToken = recaptcha_token;
if (!recaptchaToken) {
throw new Error("Token not found!");
}
const recaptchaSecretKey = process.env.RECAPTCHA_SECRET_KEY;
const data = await request.json();
const recaptchaToken = data.recaptchaToken; // Extract the reCAPTCHA token from the request

// Verify reCAPTCHA token
const recaptchaResponse = await fetch(
`https://www.google.com/recaptcha/api/siteverify?secret=${recaptchaSecretKey}&response=${recaptchaToken}`,
{ method: "POST" }
);
const recaptchaResult = await recaptchaResponse.json();
console.log(data);
console.log(recaptchaResult);
if (!recaptchaResult.success) {
// Verify the reCAPTCHA token
const isRecaptchaValid = await verifyRecaptcha(recaptchaToken);

if (!isRecaptchaValid) {
return NextResponse.json({
message: "reCAPTCHA validation failed",
error: recaptchaResult["error-codes"],
message: "reCAPTCHA verification failed",
error: true,
});
}

// Validate the data
const val = recruitValidate(data);

if (!Array.isArray(data)) {
return NextResponse.json({
message: "Expected an array of JSON objects",
error: true,
});
}

if (val.error) {
return NextResponse.json({ message: "Validation error", error: val.error });
}
Expand Down
115 changes: 60 additions & 55 deletions app/(default)/api/registration/sih/route.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,67 @@
import { db } from "@/Firebase";
import { sihValidate } from "@/lib/utils";
import { addDoc, collection, getDocs } from "firebase/firestore";
import { NextResponse } from "next/server";
import { db } from '@/Firebase';
import { sihValidate } from '@/lib/utils';
import { addDoc, collection, getDocs } from 'firebase/firestore';
import { NextResponse } from 'next/server';


// Verify reCAPTCHA Token
// async function verifyRecaptcha(token: string) {
// const secretKey = process.env.RECAPTCHA_SECRET_KEY;
// const response = await fetch(`https://www.google.com/recaptcha/api/siteverify`, {
// method: 'POST',
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
// body: new URLSearchParams({
// secret: secretKey || '',
// response: token,
// }),
// });
// const data = await response.json();
// return data.success;
// }


// Add a new registration
export async function POST(request: Request) {
const formData = await request.json();
const { recaptcha_token, ...data } = formData;
const recaptchaToken = recaptcha_token;
if (!recaptchaToken) {
throw new Error("Token not found!");
}
const recaptchaSecretKey = process.env.RECAPTCHA_SECRET_KEY;

// Verify reCAPTCHA token
const recaptchaResponse = await fetch(
`https://www.google.com/recaptcha/api/siteverify?secret=${recaptchaSecretKey}&response=${recaptchaToken}`,
{ method: "POST" }
);
const recaptchaResult = await recaptchaResponse.json();
console.log(data);
console.log(recaptchaResult);
if (!recaptchaResult.success) {
return NextResponse.json({
message: "reCAPTCHA validation failed",
error: recaptchaResult["error-codes"],
});
}

// Validate the data
const val = sihValidate(data);

if (val.error) {
return NextResponse.json({ message: "Validation error", error: val.error });
}

try {
// Save to Firebase
const docRef = await addDoc(collection(db, "sih2024"), data);
console.log("Document written with ID: ", docRef.id);
} catch (error) {
console.error(error);
return NextResponse.json({ message: "An error occurred", error });
}
// Return a response
return NextResponse.json({ message: "Registration successful", data });
const data = await request.json();
const recaptchaToken = data.recaptchaToken; // Extract the reCAPTCHA token from the request

// Verify the reCAPTCHA token
// const isRecaptchaValid = await verifyRecaptcha(recaptchaToken);

// if (!isRecaptchaValid) {
// return NextResponse.json({ message: 'reCAPTCHA verification failed', error: true });
// }

// Validate the data
const val = sihValidate(data);

if (val.error) {
return NextResponse.json({ message: 'Validation error', error: val.error });
}

try {
console.log('Data:', data);
// Save to Firebase
const docRef = await addDoc(collection(db, "sih2024"), data);
console.log("Document written with ID: ", docRef.id);
} catch (error) {
console.error(error);
return NextResponse.json({ message: 'An error occurred', error });
}
// Return a response
return NextResponse.json({ message: 'Registration successful', data });
}

//get all registrations
export async function GET() {
try {
// Get all registrations in sih2024 collection
const querySnapshot = await getDocs(collection(db, "sih2024"));
// Map the data to get only the data
const data = querySnapshot.docs.map((doc) => doc.data());
return NextResponse.json({ data });
} catch (error) {
console.error(error);
return NextResponse.json({ message: "An error occurred", error });
}
}
try {
// Get all registrations in sih2024 collection
const querySnapshot = await getDocs(collection(db, "sih2024"));
// Map the data to get only the data
const data = querySnapshot.docs.map((doc) => doc.data());
return NextResponse.json({ data });
} catch (error) {
console.error(error);
return NextResponse.json({ message: 'An error occurred', error });
}
}
33 changes: 33 additions & 0 deletions components/forms/reCaptcha.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useEffect } from "react";

const Recaptcha = ({ onChange }: { onChange: (token: string | null) => void }) => {
useEffect(() => {
const loadRecaptcha = () => {
if (window.grecaptcha) {
window.grecaptcha.ready(() => {
window.grecaptcha.execute(process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || '', { action: 'submit' }).then((token: string) => {
onChange(token);
});
});
}
};

const script = document.createElement("script");
script.src = `https://www.google.com/recaptcha/api.js?render=${process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}`;
script.async = true;
script.defer = true;
script.onload = loadRecaptcha;
document.head.appendChild(script);

return () => {
document.head.removeChild(script);
};
}, [onChange]);

return null;
};

export default Recaptcha;



54 changes: 16 additions & 38 deletions components/forms/recruitmentForm.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,17 @@
"use client";
import "../../app/css/additional-styles/utility-patterns.css";
import "../../app/css/additional-styles/theme.css";
import { useEffect, useState } from "react";
import { useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { years, branches } from "@/lib/constants/dropdownOptions";
import {
GoogleReCaptchaProvider,
GoogleReCaptcha,
} from "react-google-recaptcha-v3";
import toast from "react-hot-toast";
import Recaptcha from "./reCaptcha";

const RecruitmentForm: React.FC = () => {
const [isSuccess, setSuccess] = useState<boolean>(false);
const [mode, setMode] = useState<boolean>(false);
const [display, setDisplay] = useState<boolean>(false);
const [token, setToken] = useState("");
const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
const [recaptchaToken, setRecaptchaToken] = useState<string | null>(null);

useEffect(() => {
const script = document.createElement("script");
script.src = `https://www.google.com/recaptcha/api.js?render=your_site_key`;
script.async = true;
document.body.appendChild(script);
}, []);
const {
register,
handleSubmit,
Expand All @@ -40,32 +29,31 @@ const RecruitmentForm: React.FC = () => {
});

const changeMode = (e: any) => {
console.log(e.target.value);
if (e.target.value === "1st year") setMode(true);
else setMode(false);
setDisplay(true);
};

const setTokenFunc = (getToken: string) => {
setToken(getToken);
};

const onSubmit: SubmitHandler<any> = async (data: any) => {
try {
data.recaptcha_token = token;
if (!recaptchaToken) {
alert("Please complete the reCAPTCHA");
return;
}

const response = await fetch("/api/registration/recruitment", {

try {
let response = await fetch("/api/registration/recruitment", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
const res = await response.json();

if (!res.error) {
if (response.status == 200) {
setSuccess(true);
}
response = await response.json();
} catch (error) {
setRefreshReCaptcha(!refreshReCaptcha);
console.log("Error submitting form:", error);
console.error("Error submitting form:", error);
}
};

Expand Down Expand Up @@ -318,24 +306,14 @@ const RecruitmentForm: React.FC = () => {
)}
</div>

<Recaptcha onChange={setRecaptchaToken} />

<button
type="submit"
className="bg-green-500 text-white rounded-lg py-2 px-4 hover:bg-green-600 "
>
Submit
</button>
<GoogleReCaptchaProvider
reCaptchaKey={
process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY
? process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY
: ""
}
>
<GoogleReCaptcha
onVerify={setTokenFunc}
refreshReCaptcha={refreshReCaptcha}
/>
</GoogleReCaptchaProvider>
</div>
</form>
</div>
Expand Down
Loading

0 comments on commit 6285987

Please sign in to comment.