0x1998 - MANAGER
Düzenlenen Dosya: firebaseExamples.js
/** * Firebase Authentication and Firestore Examples * ================================================= * This file demonstrates how to import and use Firebase services * in your application using the modular Firebase v9+ syntax. * * Import Firebase services from firebase.js: */ import { auth, db } from './firebase'; // Firebase Auth functions (modular v9+) import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, onAuthStateChanged, sendPasswordResetEmail, updateProfile } from 'firebase/auth'; // Firestore functions (modular v9+) import { collection, addDoc, doc, getDoc, getDocs, updateDoc, deleteDoc, query, where, orderBy, onSnapshot } from 'firebase/firestore'; /** * ================================================================================ * AUTHENTICATION EXAMPLES * ================================================================================ */ /** * Sign Up with Email and Password * ------------------------------- * Usage in signup.js: */ export const signUpWithEmailPassword = async (email, password, displayName) => { try { // Create user with email and password const userCredential = await createUserWithEmailAndPassword(auth, email, password); const user = userCredential.user; // Optionally update the user's display name if (displayName) { await updateProfile(user, { displayName }); } console.log('User signed up:', user); return { success: true, user }; } catch (error) { console.error('Sign up error:', error.message); return { success: false, error: error.message }; } }; /** * Login with Email and Password * ----------------------------- * Usage in login.js: */ export const loginWithEmailPassword = async (email, password) => { try { const userCredential = await signInWithEmailAndPassword(auth, email, password); const user = userCredential.user; console.log('User logged in:', user); return { success: true, user }; } catch (error) { console.error('Login error:', error.message); return { success: false, error: error.message }; } }; /** * Logout * ------ * Usage in auth.js or any component: */ export const logOut = async () => { try { await signOut(auth); console.log('User logged out'); return { success: true }; } catch (error) { console.error('Logout error:', error.message); return { success: false, error: error.message }; } }; /** * Listen to Auth State Changes * ----------------------------- * Usage in auth.js (typically in a useEffect hook): * * import { useEffect, useState } from 'react'; * * const [user, setUser] = useState(null); * const [loading, setLoading] = useState(true); * * useEffect(() => { * const unsubscribe = onAuthStateChanged(auth, (currentUser) => { * setUser(currentUser); * setLoading(false); * }); * * return () => unsubscribe(); * }, []); */ export const subscribeToAuthChanges = (callback) => { return onAuthStateChanged(auth, callback); }; /** * Send Password Reset Email * ------------------------- */ export const resetPassword = async (email) => { try { await sendPasswordResetEmail(auth, email); console.log('Password reset email sent'); return { success: true }; } catch (error) { console.error('Password reset error:', error.message); return { success: false, error: error.message }; } }; /** * ================================================================================ * FIRESTORE DATABASE EXAMPLES * ================================================================================ */ /** * Create/Add a Document * --------------------- * Usage: Add a new user document after signup */ export const createUserDocument = async (userId, userData) => { try { const docRef = await addDoc(collection(db, 'users'), { ...userData, userId, createdAt: new Date(), updatedAt: new Date() }); console.log('Document written with ID:', docRef.id); return { success: true, docId: docRef.id }; } catch (error) { console.error('Error adding document:', error.message); return { success: false, error: error.message }; } }; /** * Read/Get a Single Document * --------------------------- */ export const getUserDocument = async (docId) => { try { const docSnap = await getDoc(doc(db, 'users', docId)); if (docSnap.exists()) { console.log('Document data:', docSnap.data()); return { success: true, data: docSnap.data() }; } else { console.log('No such document!'); return { success: false, error: 'No such document' }; } } catch (error) { console.error('Error getting document:', error.message); return { success: false, error: error.message }; } }; /** * Read/Get All Documents from a Collection * ----------------------------------------- */ export const getAllDocuments = async (collectionName) => { try { const querySnapshot = await getDocs(collection(db, collectionName)); const documents = []; querySnapshot.forEach((doc) => { documents.push({ id: doc.id, ...doc.data() }); }); console.log('Documents:', documents); return { success: true, data: documents }; } catch (error) { console.error('Error getting documents:', error.message); return { success: false, error: error.message }; } }; /** * Update a Document * ---------------- */ export const updateDocument = async (docId, updatedData) => { try { const docRef = doc(db, 'users', docId); await updateDoc(docRef, { ...updatedData, updatedAt: new Date() }); console.log('Document updated successfully'); return { success: true }; } catch (error) { console.error('Error updating document:', error.message); return { success: false, error: error.message }; } }; /** * Delete a Document * ---------------- */ export const deleteDocument = async (docId) => { try { await deleteDoc(doc(db, 'users', docId)); console.log('Document deleted successfully'); return { success: true }; } catch (error) { console.error('Error deleting document:', error.message); return { success: false, error: error.message }; } }; /** * Query Documents with Filters * ---------------------------- */ export const queryDocuments = async () => { try { // Example: Get documents where 'role' is 'admin', ordered by 'createdAt' const q = query( collection(db, 'users'), where('role', '==', 'admin'), orderBy('createdAt', 'desc') ); const querySnapshot = await getDocs(q); const documents = []; querySnapshot.forEach((doc) => { documents.push({ id: doc.id, ...doc.data() }); }); return { success: true, data: documents }; } catch (error) { console.error('Error querying documents:', error.message); return { success: false, error: error.message }; } }; /** * Real-time Document Updates (Listener) * ------------------------------------- * Usage: Listen for real-time updates to a document * * import { useEffect } from 'react'; * * useEffect(() => { * const unsubscribe = subscribeToDocument('users', docId, (data) => { * console.log('Document updated:', data); * }); * * return () => unsubscribe(); * }, [docId]); */ export const subscribeToDocument = (collectionName, docId, callback) => { const docRef = doc(db, collectionName, docId); return onSnapshot(docRef, (docSnap) => { if (docSnap.exists()) { callback({ id: docSnap.id, ...docSnap.data() }); } else { callback(null); } }); }; /** * ================================================================================ * EXAMPLE: Complete Sign Up Flow with User Document * ================================================================================ * * // In signup.js * import { signUpWithEmailPassword, createUserDocument } from './firebaseExamples'; * * const handleSignUp = async (email, password, displayName) => { * const result = await signUpWithEmailPassword(email, password, displayName); * * if (result.success) { * // Create a user document in Firestore * await createUserDocument(result.user.uid, { * email, * displayName, * role: 'user' * }); * console.log('Sign up successful!'); * } * }; */ /** * ================================================================================ * EXAMPLE: Complete Login Flow * ================================================================================ * * // In login.js * import { loginWithEmailPassword } from './firebaseExamples'; * * const handleLogin = async (email, password) => { * const result = await loginWithEmailPassword(email, password); * * if (result.success) { * console.log('Login successful!', result.user); * // Redirect to dashboard * } else { * console.log('Login failed:', result.error); * } * }; */ /** * ================================================================================ * EXAMPLE: Protected Route with Auth Check * ================================================================================ * * // In auth.js or a ProtectedRoute component * import { useEffect, useState } from 'react'; * import { subscribeToAuthChanges } from './firebaseExamples'; * * const ProtectedRoute = ({ children }) => { * const [user, setUser] = useState(null); * const [loading, setLoading] = useState(true); * * useEffect(() => { * const unsubscribe = subscribeToAuthChanges((currentUser) => { * setUser(currentUser); * setLoading(false); * }); * * return () => unsubscribe(); * }, []); * * if (loading) { * return <div>Loading...</div>; * } * * return user ? children : <Navigate to="/login" />; * }; */
geri dön