Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added alert for multiple account #164

Merged
merged 1 commit into from
Oct 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>;
}