Skip to content

Commit

Permalink
Fixed Login Page
Browse files Browse the repository at this point in the history
  • Loading branch information
Kalvin-Twitty committed Apr 13, 2024
1 parent 512c720 commit 9024003
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 68 deletions.
44 changes: 15 additions & 29 deletions src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import { getFirestore, doc, getDoc } from 'firebase/firestore';
import { signInWithGoogle, signOut, handleRedirectResult, signInAnonymously as firebaseSignInAnonymously, auth } from '../firebase/authService'; // Import 'auth' here
import app from '../firebase/firebaseConfig';
import { signInWithGoogle, signOut, handleRedirectResult } from '../firebase/authService';
import { addNewUserWithDisplayNameCheck } from '../firebase/userService';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [userDocumentId, setUserDocumentId] = useState(null);
const [isAdmin, setIsAdmin] = useState(false);
const [loading, setLoading] = useState(true);
const [isAdmin, setIsAdmin] = useState(false); // State to track if the current user is an admin
const [loading, setLoading] = useState(true); // Initialize loading state

useEffect(() => {
const processRedirect = async () => {
Expand All @@ -19,7 +20,10 @@ export const AuthProvider = ({ children }) => {
const db = getFirestore(app);
const userDocRef = doc(db, 'users', user.uid);
const userDoc = await getDoc(userDocRef);


console.log("User document exists:", userDoc.exists());
console.log("User admin status:", userDoc.data()?.admin);

if (!userDoc.exists()) {
await addNewUserWithDisplayNameCheck(user.uid, {
displayName: user.displayName,
Expand All @@ -31,40 +35,22 @@ export const AuthProvider = ({ children }) => {
} else {
setIsAdmin(false);
}

setCurrentUser(user);
setUserDocumentId(user.uid);
} else {
console.log("No user from redirect, likely not logged in");
console.log("Current user:", user);
console.log("Is admin:", userDoc.data()?.admin === true);
}
} catch (error) {
console.error("Error during auth redirect process:", error);
} finally {
setLoading(false);
setLoading(false); // Ensure loading is set to false after the process
}
};

processRedirect();
}, []);

const signInAnonymously = async () => {
setLoading(true);
try {
const result = await firebaseSignInAnonymously(auth); // Use 'auth' directly here
if (result && result.user) {
setCurrentUser(result.user);
setUserDocumentId(result.user.uid);
console.log("Signed in anonymously", result.user);
} else {
console.log("No user data returned on anonymous sign-in.");
}
} catch (error) {
console.error("Error signing in anonymously:", error);
} finally {
setLoading(false);
}
};

const signIn = async () => {
await signInWithGoogle();
};
Expand All @@ -75,19 +61,19 @@ export const AuthProvider = ({ children }) => {
setIsAdmin(false);
setUserDocumentId(null);
setLoading(true);
console.log("User signed out");
};

const value = {
currentUser,
userDocumentId,
isAdmin,
loading,
loading, // Include loading state in the context value
signIn,
signOut: handleSignOut,
signInAnonymously,
};

return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export const useAuth = () => useContext(AuthContext);
export const useAuth = () => useContext(AuthContext);
55 changes: 17 additions & 38 deletions src/firebase/authService.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,35 @@
import {
getAuth,
signInWithPopup,
GoogleAuthProvider,
signInWithRedirect,
getRedirectResult,
signOut as firebaseSignOut,
signInAnonymously as firebaseSignInAnonymously
} from 'firebase/auth';
import { getAuth, signInWithPopup, GoogleAuthProvider, signInWithRedirect, getRedirectResult, signOut as firebaseSignOut } from 'firebase/auth'; // Added getRedirectResult and firebaseSignOut
import app from './firebaseConfig';

const provider = new GoogleAuthProvider();
export const auth = getAuth(app); // Get and export the authentication object
const auth = getAuth(app); // Pass the Firebase app instance to getAuth

// Initiates sign-in with Google using redirect
export const signInWithGoogle = () => {
// Initiates sign-in with redirect
signInWithRedirect(auth, provider);
};

// Handles the results from the redirect sign-in
export const handleRedirectResult = async () => {
try {
const result = await getRedirectResult(auth);
if (result && result.user) {
return result.user; // Returns the user object from Firebase Auth
} else {
// Handle the case where no user is returned
console.log("No user from redirect, likely not logged in");
return null;
if (result) {
// This gives you a Google Access Token. You can use it to access Google APIs.
// The signed-in user info is now available
return result.user; // Return the user object for further processing
}
} catch (error) {
// Handle Errors here.
console.error("Error handling redirect result:", error);
throw error;
throw error; // Rethrow or handle errors appropriately
}
};

// Signs out the current user
export const signOut = async () => {
try {
await firebaseSignOut(auth);
console.log("Sign-out successful.");
} catch (error) {
export const signOut = () => {
firebaseSignOut(auth).then(() => {
// Sign-out successful.
// Update UI or redirect as needed
}).catch((error) => {
// An error happened during sign-out.
console.error("Error during sign-out:", error);
}
};

// Signs in a user anonymously
export const signInAnonymously = async () => {
try {
const result = await firebaseSignInAnonymously(auth);
return result; // Assuming you want to return the result object
} catch (error) {
console.error("Error signing in anonymously:", error);
throw error;
}
};
});
};
2 changes: 1 addition & 1 deletion src/firebase/userService.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,4 @@ export const getUserData = async (userId) => {
console.log("No such user!");
return null;
}
};
};

0 comments on commit 9024003

Please sign in to comment.