Skip to content

updated code to libs available as of June, 2022 with firebase v9 as t… #2

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
9 changes: 5 additions & 4 deletions context/AuthUserContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import useFirebaseAuth from '../lib/useFirebaseAuth';
const authUserContext = createContext({
authUser: null,
loading: true,
signInWithEmailAndPassword: async () => {},
createUserWithEmailAndPassword: async () => {},
signOut: async () => {}
signIn: async () => {},
signUp: async () => {},
logOut: async () => {},
signInWithGoogle: async () => {}
});

export function AuthUserProvider({ children }) {
const auth = useFirebaseAuth();
return <authUserContext.Provider value={auth}>{children}</authUserContext.Provider>;
}

export const useAuth = () => useContext(authUserContext);
export const useAuthUserContext = () => useContext(authUserContext);
17 changes: 8 additions & 9 deletions lib/firebase.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import firebase from 'firebase/app';
import 'firebase/auth';
import { initializeApp } from 'firebase/app';

const firebaseCredentials = {
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
}

//If an firebase app hasn't already been created
if (!firebase.apps.length) {
firebase.initializeApp(firebaseCredentials)
}

export default firebase;
export const app = initializeApp(firebaseConfig);
71 changes: 58 additions & 13 deletions lib/useFirebaseAuth.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { useState, useEffect } from 'react'
import firebase from './firebase';
import { app } from "./firebase";
import {
getAuth,
signOut,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
onAuthStateChanged,
GoogleAuthProvider,
signInWithPopup
} from 'firebase/auth';
import { useRouter } from 'next/router';

const formatAuthUser = (user) => ({
uid: user.uid,
Expand All @@ -9,6 +19,11 @@ const formatAuthUser = (user) => ({
export default function useFirebaseAuth() {
const [authUser, setAuthUser] = useState(null);
const [loading, setLoading] = useState(true);
const router = useRouter();

const auth = getAuth(app)
const provider = new GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });

const authStateChanged = async (authState) => {
if (!authState) {
Expand All @@ -28,28 +43,58 @@ export default function useFirebaseAuth() {

const clear = () => {
setAuthUser(null);
setLoading(true);
setLoading(false);
};

const signInWithEmailAndPassword = (email, password) =>
firebase.auth().signInWithEmailAndPassword(email, password);
const signIn = (email, password) =>
signInWithEmailAndPassword(auth, email, password)
.then(authUser => {
console.log("Success. The user is created in firebase")
router.push('/logged_in');
})
.catch(error => {
setError(error.message)
});

const createUserWithEmailAndPassword = (email, password) =>
firebase.auth().createUserWithEmailAndPassword(email, password);
const signUp = (email, password) =>
createUserWithEmailAndPassword(auth, email, password);

const signOut = () =>
firebase.auth().signOut().then(clear);
const logOut = () =>
signOut(auth).then(clear)

useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(authStateChanged);
return () => unsubscribe();
const unsubscribe = onAuthStateChanged(auth, authStateChanged);
return unsubscribe
}, []);

const signInWithGoogle = () =>
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// redux action? --> dispatch({ type: SET_USER, user });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commented code should not be pushed to GitHub.

router.push('/logged_in');
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});

return {
authUser,
loading,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut
signIn,
signUp,
logOut,
signInWithGoogle
};
}
Loading