Skip to content

Commit

Permalink
Merge pull request #164 from tusharshah21/main
Browse files Browse the repository at this point in the history
added alert for multiple account
  • Loading branch information
DhanushNehru authored Oct 27, 2024
2 parents 2c70db8 + 0057389 commit 2de02e2
Showing 1 changed file with 31 additions and 12 deletions.
43 changes: 31 additions & 12 deletions src/context/AuthContext.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// src/context/AuthContext.js
import { onAuthStateChanged, signOut } from "firebase/auth";
import { onAuthStateChanged, signOut, fetchSignInMethodsForEmail, signInWithPopup } from "firebase/auth";
import React, { useContext, useEffect, useState } from "react";
import { GithubAuthProvider, GoogleAuthProvider, auth, signInWithPopup } from "../components/firebase";
import { GithubAuthProvider, GoogleAuthProvider, auth } from "../components/firebase";

const AuthContext = React.createContext();

Expand All @@ -12,15 +11,36 @@ export function useAuth() {
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState(null);

const googleSignIn = ()=>{
const googleSignIn = async () => {
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider);
}
const githubSignIn = ()=>{
await signInWithPopup(auth, provider);
};

const githubSignIn = async () => {
const provider = new GithubAuthProvider();
signInWithPopup(auth, provider);
}

try {
// Attempt to sign in with GitHub
const result = await signInWithPopup(auth, provider);
return result.user;
} catch (error) {
// Check if the error is for an existing account
if (error.code === "auth/account-exists-with-different-credential") {
const email = error.customData.email;
const signInMethods = await fetchSignInMethodsForEmail(auth, email);
if (signInMethods.includes("google.com")) {
// If the existing account is Google, sign in with Google instead
alert("You already have an account with this email using Google. Signing you in with Google now.");
const googleProvider = new GoogleAuthProvider();
const googleResult = await signInWithPopup(auth, googleProvider);
return googleResult.user;
} else {
alert("An account already exists with this email. Please sign in using one of the other method");
}
}
throw error;
}
};

function logOut() {
signOut(auth);
Expand All @@ -32,8 +52,7 @@ export function AuthProvider({ children }) {
});

return () => unsubscribe();
}, [currentUser]);

}, []);

return <AuthContext.Provider value={{ currentUser, googleSignIn, githubSignIn, logOut }}>{children}</AuthContext.Provider>;
}

0 comments on commit 2de02e2

Please sign in to comment.