Spaces:
Running
Running
File size: 2,618 Bytes
2bb4273 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | import { createContext, useContext, useEffect, useState } from 'react'
import { initializeApp } from 'firebase/app'
import { getAuth, GoogleAuthProvider, signInWithPopup, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut } from 'firebase/auth'
import { getFirestore, collection, doc, setDoc, getDoc, getDocs, query, where, orderBy, onSnapshot } from 'firebase/firestore'
const FirebaseContext = createContext()
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY || "demo-key",
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN || "demo.firebaseapp.com",
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID || "demo-project",
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET || "demo.appspot.com",
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID || "123456789",
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID || "1:123456789:web:abc123"
}
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)
const db = getFirestore(app)
export function FirebaseProvider({ children }) {
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
setUser(user)
setLoading(false)
})
return unsubscribe
}, [])
const signInWithGoogle = async () => {
const provider = new GoogleAuthProvider()
try {
await signInWithPopup(auth, provider)
} catch (error) {
console.error('Google sign in error:', error)
}
}
const signInWithEmail = async (email, password) => {
try {
await signInWithEmailAndPassword(auth, email, password)
} catch (error) {
console.error('Email sign in error:', error)
throw error
}
}
const signUpWithEmail = async (email, password) => {
try {
await createUserWithEmailAndPassword(auth, email, password)
} catch (error) {
console.error('Email sign up error:', error)
throw error
}
}
const logout = async () => {
try {
await signOut(auth)
} catch (error) {
console.error('Logout error:', error)
}
}
const value = {
user,
loading,
auth,
db,
signInWithGoogle,
signInWithEmail,
signUpWithEmail,
logout
}
return (
<FirebaseContext.Provider value={value}>
{children}
</FirebaseContext.Provider>
)
}
export const useFirebase = () => {
const context = useContext(FirebaseContext)
if (!context) {
throw new Error('useFirebase must be used within FirebaseProvider')
}
return context
} |