-
-
Notifications
You must be signed in to change notification settings - Fork 63
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #210 from RishabhRawatt/main
[FEATURE] Adding Rate limiting to the OTP verify
- Loading branch information
Showing
6 changed files
with
124 additions
and
72 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,3 @@ | ||
|
||
import { db } from "@/lib/drizzle"; | ||
import { otps } from "@/lib/schema"; | ||
import { NextRequest, NextResponse } from "next/server"; | ||
|
@@ -8,66 +7,61 @@ import otpEmailTemplate from "@/lib/templates/otp-template"; | |
import { auth } from "@/auth"; | ||
import mailer from "@/lib/mailer"; | ||
|
||
|
||
|
||
// `[email protected]` email is for development only | ||
const senderEmail = process.env.SENDER_EMAIL || "[email protected]"; | ||
|
||
|
||
export async function POST(req: NextRequest) { | ||
try { | ||
const session = await auth(); | ||
if (!session) throw new Error("Login first to verify email") | ||
if (!session) throw new Error("Login first to verify email"); | ||
|
||
const userWithEmail = await db.query.users.findFirst({ | ||
where: (users, { eq }) => eq(users.email, session.user.email!), | ||
}); | ||
|
||
if (!userWithEmail) throw new Error("User with email not exists."); | ||
|
||
|
||
const prevOtps = await db.query.otps.findMany({ | ||
where: (otps, { eq }) => eq(otps.userId, userWithEmail.id), | ||
orderBy: (otps, { desc }) => desc(otps.expiresAt), | ||
}) | ||
}); | ||
|
||
// Check if there is a valid OTP | ||
const now = new Date(); | ||
const validOtp = prevOtps.find(otp => otp.expiresAt > now); | ||
const validOtp = prevOtps.find((otp) => otp.expiresAt > now); | ||
|
||
if (validOtp) { | ||
const remainingTimeInSeconds = Math.floor((validOtp.expiresAt.getTime() - now.getTime()) / 1000); // Time in seconds | ||
const remainingTimeInSeconds = Math.floor( | ||
(validOtp.expiresAt.getTime() - now.getTime()) / 1000 | ||
); // Time in seconds | ||
const minutes = Math.floor(remainingTimeInSeconds / 60); // Full minutes | ||
const seconds = remainingTimeInSeconds % 60; // Remaining seconds | ||
|
||
return NextResponse.json({ message: `Please wait ${minutes} minutes and ${seconds} seconds before resending the OTP.` }, { status: 429 }); | ||
return NextResponse.json( | ||
{ | ||
message: `Please wait ${minutes} minutes and ${seconds} seconds before resending the OTP.`, | ||
}, | ||
{ status: 429 } | ||
); | ||
} | ||
|
||
const otp = Math.floor(100000 + Math.random() * 900000).toString(); // 6-digit OTP | ||
// Set expiration time (e.g., 10 minutes from now) | ||
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes in the future | ||
|
||
|
||
|
||
await db.insert(otps).values({ | ||
expiresAt, | ||
otp, | ||
userId: userWithEmail.id, | ||
createdAt: new Date(), | ||
}); | ||
|
||
|
||
|
||
|
||
await mailer.sendMail({ | ||
from: `Uttarakhand Culture <${senderEmail}>`, | ||
to: [userWithEmail.email!], | ||
subject: 'Verify you email with OTP', | ||
subject: "Verify you email with OTP", | ||
html: otpEmailTemplate(userWithEmail.name!, otp), | ||
}) | ||
|
||
|
||
|
||
}); | ||
|
||
return NextResponse.json({ | ||
message: `OTP has been resent to your email.`, | ||
|
@@ -79,4 +73,4 @@ export async function POST(req: NextRequest) { | |
console.log("[OTP_RESEND_ERROR]: ", error); | ||
return NextResponse.json({ error: error.message }, { status: 500 }); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,41 +1,46 @@ | ||
"use client"; | ||
import {useSession, signOut} from "next-auth/react"; | ||
import {useRouter} from "next/navigation"; | ||
import { useSession, signOut } from "next-auth/react"; | ||
import { useRouter } from "next/navigation"; | ||
import styles from "./profile.module.css"; | ||
import Image from "next/image"; | ||
|
||
export default function Profile() { | ||
const {data: session, status} = useSession(); | ||
const router = useRouter(); | ||
const { data: session, status } = useSession(); | ||
const router = useRouter(); | ||
|
||
if (status === "loading") { | ||
return <p>Loading...</p>; | ||
} | ||
if (status === "loading") { | ||
return <p>Loading...</p>; | ||
} | ||
|
||
if (status === "unauthenticated") { | ||
router.push("/"); // Redirect to login if unauthenticated | ||
return null; | ||
} | ||
if (status === "unauthenticated") { | ||
router.push("/"); // Redirect to login if unauthenticated | ||
return null; | ||
} | ||
|
||
return ( | ||
<div className={styles["profile-container"]}> | ||
<h1 className={styles["profile-heading"]}>User Profile</h1> | ||
<div className={styles["profile-details"]}> | ||
<Image src={session?.user?.image || "/default-avatar.png"} alt="User Avatar" | ||
className={styles["profile-avatar"]}/> | ||
<p> | ||
<strong>Name:</strong> {session?.user?.name || "N/A"} | ||
</p> | ||
<p> | ||
<strong>Email:</strong> {session?.user?.email || "N/A"} | ||
</p> | ||
</div> | ||
<button | ||
onClick={() => signOut({redirect: false})} | ||
className={styles["logout-button"]} | ||
> | ||
Logout | ||
</button> | ||
</div> | ||
); | ||
return ( | ||
<div className={styles["profile-container"]}> | ||
<h1 className={styles["profile-heading"]}>User Profile</h1> | ||
<div className={styles["profile-details"]}> | ||
<Image | ||
src={session?.user?.image || "/default-avatar.png"} | ||
alt="User Avatar" | ||
className={styles["profile-avatar"]} | ||
width={250} | ||
height={250} | ||
/> | ||
<p> | ||
<strong>Name:</strong> {session?.user?.name || "N/A"} | ||
</p> | ||
<p> | ||
<strong>Email:</strong> {session?.user?.email || "N/A"} | ||
</p> | ||
</div> | ||
<button | ||
onClick={() => signOut({ redirect: false })} | ||
className={styles["logout-button"]} | ||
> | ||
Logout | ||
</button> | ||
</div> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters