@jager-ai/holy-auth-firebase
v1.0.0
Published
Firebase Authentication module with Google Sign-In support
Maintainers
Readme
@mvp-factory/holy-auth-firebase
Firebase Authentication module with Google Sign-In support. Extracted from Holy Habit Phase 2 authentication system.
🚀 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
npm install @mvp-factory/holy-auth-firebase
# or
yarn add @mvp-factory/holy-auth-firebase
# or
pnpm add @mvp-factory/holy-auth-firebasePeer Dependencies
npm install firebase@^10.0.0For server-side token verification:
npm install jsonwebtoken@^9.0.0🔧 Quick Start
1. Basic Setup
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
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.
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): voidAuthenticated Fetch Utilities
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
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
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
interface FirebaseConfig {
apiKey: string;
authDomain: string;
projectId: string;
storageBucket?: string;
messagingSenderId?: string;
appId: string;
measurementId?: string;
}🔥 Firebase Console Setup
Go to Firebase Console
Create a new project or select existing
Enable Authentication service
Enable Google Sign-In provider:
- Authentication → Sign-in method → Google → Enable
- Configure OAuth consent screen
- Add authorized domains
Get your configuration:
- Project Settings → General → Your apps → Web app
- Copy the configuration object
🔐 Backend Integration
PHP Backend Example
// 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
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
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
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
// Mock Firebase Auth for testing
import { FirebaseAuthManager } from '@mvp-factory/holy-auth-firebase';
// In your test setup
const mockUser = {
uid: 'test-uid',
email: '[email protected]',
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 - OAuth social login
- @mvp-factory/holy-editor - Rich text editor
- @mvp-factory/holy-upload - File upload utilities
- @mvp-factory/holy-pwa - PWA configuration
- @mvp-factory/holy-bible-api - Bible verse API
