Skip to content

Commit fd99d9f

Browse files
committed
Add email existence validation to forgot password feature
1 parent 6fd7528 commit fd99d9f

2 files changed

Lines changed: 25 additions & 3 deletions

File tree

src/app/auth/forgot-password/page.tsx

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"use client";
22

33
import { useState } from "react";
4-
import { resetPassword } from "@/lib/firebase/auth";
4+
import { resetPassword, checkEmailExists } from "@/lib/firebase/auth";
55
import Link from "next/link";
66
import { Mail, ArrowLeft } from "lucide-react";
77
import { useToast } from "@/context/ToastContext";
@@ -24,10 +24,20 @@ export default function ForgotPasswordPage() {
2424
}
2525

2626
try {
27+
// Check if email exists
28+
const emailExists = await checkEmailExists(email);
29+
30+
if (!emailExists) {
31+
addToast("No account found with this email address.", "error");
32+
setLoading(false);
33+
return;
34+
}
35+
36+
// Send password reset email
2737
await resetPassword(email);
2838
addToast("Password reset email sent! Check your inbox.", "success");
2939
} catch (err: any) {
30-
addToast("Can't reset password. Please check the email and try again.", "error");
40+
addToast("Can't reset password. Please try again.", "error");
3141
console.error(err);
3242
} finally {
3343
setLoading(false);

src/lib/firebase/auth.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import {
77
updateProfile,
88
User,
99
sendPasswordResetEmail,
10-
sendEmailVerification
10+
sendEmailVerification,
11+
fetchSignInMethodsForEmail
1112
} from "firebase/auth";
1213
import { useEffect, useState } from "react";
1314
import { isAllowedEmail } from "../config";
@@ -59,6 +60,17 @@ export const signUp = async (name: string, email: string, pass: string) => {
5960
// Sign Out
6061
export const signOut = () => firebaseSignOut(auth);
6162

63+
// Check if email exists
64+
export const checkEmailExists = async (email: string): Promise<boolean> => {
65+
try {
66+
const methods = await fetchSignInMethodsForEmail(auth, email);
67+
return methods.length > 0;
68+
} catch (error) {
69+
console.error("Error checking email:", error);
70+
return false;
71+
}
72+
};
73+
6274
// Password Reset
6375
export const resetPassword = (email: string) =>
6476
sendPasswordResetEmail(auth, email);

0 commit comments

Comments
 (0)