UNPKG

@mvp-factory/holy-auth-firebase

Version:

Firebase Authentication module with Google Sign-In support

355 lines (275 loc) โ€ข 9.4 kB
# @mvp-factory/holy-auth-firebase > Firebase Authentication module with Google Sign-In support. Extracted from Holy Habit Phase 2 authentication system. <p align="center"> <img src="https://img.shields.io/npm/v/@mvp-factory/holy-auth-firebase" alt="npm version" /> <img src="https://img.shields.io/npm/l/@mvp-factory/holy-auth-firebase" alt="license" /> <img src="https://img.shields.io/npm/dt/@mvp-factory/holy-auth-firebase" alt="downloads" /> </p> ## ๐Ÿš€ Features - โœ… **Google Sign-In** - One-click Google authentication - ๐Ÿ”’ **Token Management** - Automatic ID token handling and refresh - ๐Ÿ”„ **Backend Sync** - Automatic session synchronization with backend - ๐Ÿ›ก๏ธ **Server-side Verification** - JWT token verification utilities - ๐ŸŽฏ **TypeScript Support** - Full type definitions included - ๐Ÿ”Œ **Event System** - Subscribe to auth state changes - ๐Ÿ’พ **Auto-save Integration** - Built-in auto-save functionality - ๐Ÿ” **Authenticated Fetch** - HTTP utilities with automatic token attachment ## ๐Ÿ“ฆ Installation ```bash npm install @mvp-factory/holy-auth-firebase # or yarn add @mvp-factory/holy-auth-firebase # or pnpm add @mvp-factory/holy-auth-firebase ``` ### Peer Dependencies ```bash npm install firebase@^10.0.0 ``` For server-side token verification: ```bash npm install jsonwebtoken@^9.0.0 ``` ## ๐Ÿ”ง Quick Start ### 1. Basic Setup ```typescript import { initializeFirebaseAuth } from '@mvp-factory/holy-auth-firebase'; // Initialize Firebase Auth const authManager = await initializeFirebaseAuth({ apiKey: "your-api-key", authDomain: "your-auth-domain", projectId: "your-project-id", appId: "your-app-id" }); // Sign in with Google const result = await authManager.signInWithGoogle(); console.log('Signed in:', result.user.email); ``` ### 2. With React ```tsx import { FirebaseAuthManager, updateAuthUI } from '@mvp-factory/holy-auth-firebase'; function App() { const [user, setUser] = useState(null); useEffect(() => { const authManager = FirebaseAuthManager.getInstance(); // Listen to auth state changes const unsubscribe = authManager.on('auth_state_changed', (event, data) => { setUser(data.user); updateAuthUI(!!data.user, data.user); }); return unsubscribe; }, []); const handleLogin = async () => { try { await authManager.signInWithGoogle(); } catch (error) { console.error('Login failed:', error); } }; return ( <div> {user ? ( <p>Welcome, {user.email}!</p> ) : ( <button onClick={handleLogin}>Sign in with Google</button> )} </div> ); } ``` ## ๐Ÿ“– API Reference ### FirebaseAuthManager Singleton class for managing Firebase authentication. ```typescript const authManager = FirebaseAuthManager.getInstance(options?: AuthOptions); // Methods authManager.initialize(config: FirebaseConfig): Promise<void> authManager.signInWithGoogle(customParams?: Record<string, string>): Promise<SignInResult> authManager.signOut(): Promise<void> authManager.getCurrentUser(): AuthUser | null authManager.getAuthState(): AuthState authManager.getIdToken(forceRefresh?: boolean): Promise<string | null> authManager.isAuthenticated(): boolean // Events authManager.on(event: AuthEvent, listener: AuthEventListener): () => void authManager.off(event: AuthEvent, listener: AuthEventListener): void ``` ### Authenticated Fetch Utilities ```typescript import { authenticatedFetch, authenticatedJSON, createAuthenticatedClient } from '@mvp-factory/holy-auth-firebase'; // Simple authenticated fetch const response = await authenticatedFetch('/api/data'); // Fetch JSON with authentication const data = await authenticatedJSON('/api/users'); // Create authenticated client const api = createAuthenticatedClient('https://api.example.com'); const users = await api.get('/users'); const newUser = await api.post('/users', { name: 'John' }); ``` ### Server-side Token Verification ```typescript import { TokenVerifier, createAuthMiddleware } from '@mvp-factory/holy-auth-firebase'; // Express middleware app.use(createAuthMiddleware('your-project-id')); // Manual verification const verifier = new TokenVerifier('your-project-id'); const result = await verifier.verifyIdToken(idToken); if (result) { console.log('Verified user:', result.uid, result.email); } ``` ## โš™๏ธ Configuration ### AuthOptions ```typescript interface AuthOptions { persistence?: 'local' | 'session' | 'none'; // Default: 'local' customParameters?: Record<string, string>; // Google OAuth custom params scopes?: string[]; // Additional OAuth scopes autoSync?: boolean; // Auto sync with backend (default: true) syncEndpoint?: string; // Backend sync endpoint (default: '/api/auth/firebase/sync') } ``` ### Firebase Configuration ```typescript interface FirebaseConfig { apiKey: string; authDomain: string; projectId: string; storageBucket?: string; messagingSenderId?: string; appId: string; measurementId?: string; } ``` ## ๐Ÿ”ฅ Firebase Console Setup 1. Go to [Firebase Console](https://console.firebase.google.com/) 2. Create a new project or select existing 3. Enable Authentication service 4. Enable Google Sign-In provider: - Authentication โ†’ Sign-in method โ†’ Google โ†’ Enable - Configure OAuth consent screen - Add authorized domains 5. Get your configuration: - Project Settings โ†’ General โ†’ Your apps โ†’ Web app - Copy the configuration object ## ๐Ÿ” Backend Integration ### PHP Backend Example ```php // api/auth/firebase/sync.php <?php require_once '../vendor/autoload.php'; use Firebase\JWT\JWT; use Firebase\JWT\Key; // Get ID token from Authorization header $headers = getallheaders(); $authHeader = $headers['Authorization'] ?? ''; if (!str_starts_with($authHeader, 'Bearer ')) { http_response_code(401); die(json_encode(['error' => 'Unauthorized'])); } $idToken = substr($authHeader, 7); // Verify token (implement your verification logic) try { // Decode and verify the token $decoded = verifyFirebaseToken($idToken); // Create/update session $_SESSION['user_uid'] = $decoded->sub; $_SESSION['user_email'] = $decoded->email; echo json_encode([ 'success' => true, 'user' => [ 'uid' => $decoded->sub, 'email' => $decoded->email, 'name' => $decoded->name ] ]); } catch (Exception $e) { http_response_code(401); echo json_encode(['error' => 'Invalid token']); } ``` ### Node.js Backend Example ```javascript const express = require('express'); const { createAuthMiddleware } = require('@mvp-factory/holy-auth-firebase'); const app = express(); // Apply auth middleware app.use('/api/*', createAuthMiddleware('your-project-id')); // Protected route app.get('/api/profile', (req, res) => { // req.user contains verified user info res.json({ uid: req.user.uid, email: req.user.email }); }); ``` ## ๐ŸŽฏ Use Cases ### Auto-save with Authentication ```typescript import { setupAutoSave, getAutoSavedContent } from '@mvp-factory/holy-auth-firebase'; // Setup auto-save const cleanup = setupAutoSave( () => document.getElementById('content').value, { interval: 30000, // 30 seconds key: 'my_app_autosave', onSave: (data) => console.log('Saved:', data), onError: (error) => console.error('Save failed:', error) } ); // Restore saved content const saved = getAutoSavedContent('my_app_autosave'); if (saved) { document.getElementById('content').value = saved.content; } ``` ### Protected API Calls ```typescript const api = createAuthenticatedClient('https://api.example.com'); // All requests automatically include auth token try { const profile = await api.get('/user/profile'); const posts = await api.get('/user/posts'); // Upload with authentication const file = document.getElementById('file').files[0]; const upload = await api.upload('/upload', file, { fieldName: 'avatar' }); } catch (error) { if (error.message.includes('401')) { // Token expired or invalid await authManager.signOut(); } } ``` ## ๐Ÿงช Testing ```typescript // Mock Firebase Auth for testing import { FirebaseAuthManager } from '@mvp-factory/holy-auth-firebase'; // In your test setup const mockUser = { uid: 'test-uid', email: 'test@example.com', displayName: 'Test User' }; // Mock the sign in method jest.spyOn(authManager, 'signInWithGoogle').mockResolvedValue({ user: mockUser, token: 'mock-token' }); ``` ## ๐Ÿค Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## ๐Ÿ“ License MIT ยฉ MVP Factory ## ๐Ÿ”— Related Packages - [@mvp-factory/holy-oauth](https://www.npmjs.com/package/@mvp-factory/holy-oauth) - OAuth social login - [@mvp-factory/holy-editor](https://www.npmjs.com/package/@mvp-factory/holy-editor) - Rich text editor - [@mvp-factory/holy-upload](https://www.npmjs.com/package/@mvp-factory/holy-upload) - File upload utilities - [@mvp-factory/holy-pwa](https://www.npmjs.com/package/@mvp-factory/holy-pwa) - PWA configuration - [@mvp-factory/holy-bible-api](https://www.npmjs.com/package/@mvp-factory/holy-bible-api) - Bible verse API --- <p align="center"> Made with โค๏ธ by <a href="https://github.com/mvp-factory">MVP Factory</a> </p>