Shared Firebase Cloud Functions modules
npm install @zssz-soft/firebase-functions-sharedA shared library of Firebase Cloud Functions modules for LodgeFlow applications. This library provides common functionality for user management, email services, file storage, and system bootstrap across multiple Firebase projects.
- Bootstrap Module: System initialization with default admin user and roles
- Email Module: Templated email service (welcome, password reset, notifications)
- Storage Module: Image/document processing with thumbnail generation and HEIC conversion
- User Module: User management with Firebase Auth and Firestore integration
- Configuration Management: Centralized configuration for multi-tenant deployments
``bash`
cd firebase/shared/functions
npm install
npm run build
Before using any shared functions, you must initialize the application configuration in your main index.ts file:
`typescript
import { initializeApp } from 'firebase-admin/app';
import { setGlobalOptions } from 'firebase-functions/v2';
import { initializeConfig, AppConfig } from '@lodgeflow/firebase-functions-shared';
// Initialize Firebase Admin SDK
initializeApp({
projectId: process.env.GCLOUD_PROJECT || 'your-project-id',
});
// Configure shared library
const config: AppConfig = {
projectId: process.env.GCLOUD_PROJECT || 'your-project-id',
region: process.env.FUNCTION_REGION || 'europe-west1',
firestoreDatabaseId: process.env.FIRESTORE_DATABASE_ID, // Optional
appName: 'Your App Name',
defaultAdminPassword: process.env.DEFAULT_ADMIN_PASSWORD || 'AdminBootstrap2024!',
defaultUserPassword: process.env.DEFAULT_USER_PASSWORD || 'User2024!',
defaultAdminRoleId: '66000',
defaultUserRoleId: '66001',
defaultLoginUrl: process.env.DEFAULT_LOGIN_URL || 'https://yourapp.web.app/login',
maxInstances: 10,
};
initializeConfig(config);
// Set global function options
setGlobalOptions({
maxInstances: config.maxInstances,
region: config.region,
});
// Export functions
export * from '@lodgeflow/firebase-functions-shared';
`
Create a .env file in your functions directory:
`bashFirebase Configuration
GCLOUD_PROJECT=your-project-id
FUNCTION_REGION=europe-west1
FIRESTORE_DATABASE_ID=default # Optional
$3
#### Bootstrap Module
Initialize your system with default admin user and roles:
`typescript
// Client-side usage
import { getFunctions, httpsCallable } from 'firebase/functions';const functions = getFunctions();
const systemBootstrap = httpsCallable(functions, 'systemBootstrap');
const result = await systemBootstrap({
adminEmail: 'admin@yourapp.com',
adminDisplayName: 'Admin User',
adminPassword: 'SecurePassword123!',
});
console.log(result.data.message);
`Check bootstrap status:
`typescript
const checkStatus = httpsCallable(functions, 'checkBootstrapStatus');
const status = await checkStatus();
console.log(status.data); // { isBootstrapped: true, userCount: 1 }
`#### Email Module
Send templated emails:
`typescript
const sendEmail = httpsCallable(functions, 'sendEmail');// Welcome email
await sendEmail({
to: 'user@example.com',
subject: 'Welcome!',
type: 'welcome',
userName: 'John Doe',
loginLink: 'https://yourapp.web.app/login',
});
// Password reset email
await sendEmail({
to: 'user@example.com',
subject: 'Reset Password',
type: 'password-reset',
userName: 'John Doe',
resetLink: 'https://yourapp.web.app/reset?token=abc123',
});
// Notification email
await sendEmail({
to: 'user@example.com',
subject: 'Important Update',
type: 'notification',
message: 'Your account has been updated.',
});
`#### Storage Module
Generate thumbnails for images and documents:
`typescript
const generateThumbnail = httpsCallable(functions, 'generateThumbnail');const result = await generateThumbnail({
path: 'gs://your-bucket/path/to/image.jpg',
maxWidth: 512,
maxHeight: 512,
force: false, // Set to true to regenerate existing thumbnails
documentId: 'optional-document-id', // Updates Firestore document with thumbnail URL
});
console.log(result.data);
// {
// success: true,
// path: 'path/to/image.jpg',
// thumbPath: 'https://.../_thumb.webp',
// webImagePath: 'https://.../_web.jpg', // For HEIC files only
// created: true
// }
`#### User Module
Create users with automatic email notification:
`typescript
const createUser = httpsCallable(functions, 'createUserWithEmail');const result = await createUser({
email: 'newuser@example.com',
firstName: 'John',
lastName: 'Doe',
password: 'SecurePassword123!',
phoneNumber: '+1234567890',
roleIds: ['66001'], // USER role
sendWelcomeEmail: true,
loginUrl: 'https://yourapp.web.app/login',
});
console.log(result.data);
// { success: true, uid: '...', email: '...', emailSent: true }
`Module Details
$3
Functions:
-
systemBootstrap(data) - Creates initial admin user and default roles
- checkBootstrapStatus() - Checks if system has been initializedDefault Roles:
- ADMIN (ID: 66000): Full administrative access
- USER (ID: 66001): Standard user access
$3
Supported Email Types:
-
welcome - Welcome email with login link
- password-reset - Password reset email with reset link
- notification - Generic notification email
- custom - Custom HTML emailConfiguration:
All emails use the application name from the configuration and support both HTML and plain text formats.
$3
Supported File Types:
- Images: jpg, jpeg, png, webp, avif, gif, bmp, tiff, heic, heif
- Documents: pdf, doc, docx, xls, xlsx, ppt, pptx, txt, rtf, odt, ods, odp
Features:
- Automatic HEIC to JPEG conversion (web-optimized)
- WebP thumbnail generation (512x512 default)
- Empty placeholder thumbnails for non-image files
- Automatic Firestore document updates with thumbnail URLs
- Efficient caching (1 year max-age)
$3
Features:
- Creates users in both Firebase Auth and Firestore
- Automatic welcome email sending
- Default role assignment (USER role)
- Transaction-safe with automatic cleanup on errors
- Supports custom passwords or generates secure defaults
Configuration Reference
$3
`typescript
interface AppConfig {
projectId: string; // Firebase project ID
region: string; // Cloud Functions region
firestoreDatabaseId?: string; // Optional Firestore database ID
appName: string; // Application name for branding
defaultAdminPassword: string; // Bootstrap admin password
defaultUserPassword: string; // Default password for new users
defaultAdminRoleId: string; // Admin role ID in Firestore
defaultUserRoleId: string; // User role ID in Firestore
defaultLoginUrl: string; // Default login URL for emails
maxInstances?: number; // Max Cloud Function instances
}
`$3
`typescript
interface EmailConfig {
host: string; // SMTP server hostname
port: number; // SMTP port (587 or 465)
secure: boolean; // TLS/SSL enabled
user: string; // SMTP username
pass: string; // SMTP password
fromName: string; // Sender display name
fromEmail: string; // Sender email address
}
`Security Best Practices
1. Environment Variables: Store sensitive data in environment variables, not in code
2. Firebase Secrets: Use Firebase Secrets Manager for production:
`bash
firebase functions:secrets:set EMAIL_PASS
`
3. Authentication: All functions require authentication except bootstrap status check
4. Role-Based Access: Implement proper role checks in your application
5. Password Policies: Enforce strong passwords (min 6 characters)
6. Email Verification: Users should verify their email addressesDevelopment
$3
`bash
npm run build
`$3
`bash
npm run build:watch
`$3
`bash
npm test
`$3
`bash
npm run lint
`Migration Guide
$3
1. Install the shared library in your Firebase functions project
2. Update your index.ts to initialize configuration
3. Remove duplicate code from your project (bootstrap, email, storage, user modules)
4. Update imports to use the shared library
5. Configure environment variables according to the template above
6. Test thoroughly in emulator before deploying
Example migration:
`typescript
// Before
import { systemBootstrap } from './modules/bootstrap/bootstrap';
export { systemBootstrap };// After
import { initializeConfig, AppConfig } from '@lodgeflow/firebase-functions-shared';
const config: AppConfig = {
/ your config /
};
initializeConfig(config);
export * from '@lodgeflow/firebase-functions-shared';
`Contributing
This is a private shared library for LodgeFlow applications. To contribute:
1. Make changes in the
firebase/shared/functions directory
2. Test changes in emulator with one of the consumer projects
3. Update version in package.json
4. Build and deployTroubleshooting
$3
Error:
Application configuration not initialized. Call initializeConfig() first.Solution: Ensure you call
initializeConfig(config) before exporting any functions.$3
Error:
Email configuration incompleteSolution: Check that all required environment variables are set (EMAIL_HOST, EMAIL_USER, EMAIL_PASS).
$3
Error:
Firestore database "default" not foundSolution: Either create the database in Firebase Console or set
firestoreDatabaseId to undefined to use the default database.$3
Error:
Failed to convert HEIC to JPEGSolution: Ensure
heic-convert and sharp` are installed. Check that the file is a valid HEIC image.UNLICENSED - Private library for ZS-Soft/LodgeFlow applications.
For issues or questions, contact the development team or create an issue in the project repository.