@zssz-soft/firebase-functions-shared
v1.2.6
Published
Shared Firebase Cloud Functions modules for LodgeFlow applications
Maintainers
Readme
LodgeFlow Shared Firebase Functions
A 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.
Features
- 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
Installation
cd firebase/shared/functions
npm install
npm run buildUsage
1. Initialize Configuration
Before using any shared functions, you must initialize the application configuration in your main index.ts file:
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';2. Environment Variables
Create a .env file in your functions directory:
# Firebase Configuration
GCLOUD_PROJECT=your-project-id
FUNCTION_REGION=europe-west1
FIRESTORE_DATABASE_ID=default # Optional
# Email Configuration (SMTP)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
[email protected]
EMAIL_PASS=your-app-password
EMAIL_FROM_NAME=Your App Name
[email protected]
# Application Configuration
DEFAULT_ADMIN_PASSWORD=AdminBootstrap2024!
DEFAULT_USER_PASSWORD=User2024!
DEFAULT_LOGIN_URL=https://yourapp.web.app/login3. Using Shared Modules
Bootstrap Module
Initialize your system with default admin user and roles:
// Client-side usage
import { getFunctions, httpsCallable } from 'firebase/functions';
const functions = getFunctions();
const systemBootstrap = httpsCallable(functions, 'systemBootstrap');
const result = await systemBootstrap({
adminEmail: '[email protected]',
adminDisplayName: 'Admin User',
adminPassword: 'SecurePassword123!',
});
console.log(result.data.message);Check bootstrap status:
const checkStatus = httpsCallable(functions, 'checkBootstrapStatus');
const status = await checkStatus();
console.log(status.data); // { isBootstrapped: true, userCount: 1 }Email Module
Send templated emails:
const sendEmail = httpsCallable(functions, 'sendEmail');
// Welcome email
await sendEmail({
to: '[email protected]',
subject: 'Welcome!',
type: 'welcome',
userName: 'John Doe',
loginLink: 'https://yourapp.web.app/login',
});
// Password reset email
await sendEmail({
to: '[email protected]',
subject: 'Reset Password',
type: 'password-reset',
userName: 'John Doe',
resetLink: 'https://yourapp.web.app/reset?token=abc123',
});
// Notification email
await sendEmail({
to: '[email protected]',
subject: 'Important Update',
type: 'notification',
message: 'Your account has been updated.',
});Storage Module
Generate thumbnails for images and documents:
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:
const createUser = httpsCallable(functions, 'createUserWithEmail');
const result = await createUser({
email: '[email protected]',
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
Bootstrap Module
Functions:
systemBootstrap(data)- Creates initial admin user and default rolescheckBootstrapStatus()- Checks if system has been initialized
Default Roles:
- ADMIN (ID: 66000): Full administrative access
- USER (ID: 66001): Standard user access
Email Module
Supported Email Types:
welcome- Welcome email with login linkpassword-reset- Password reset email with reset linknotification- Generic notification emailcustom- Custom HTML email
Configuration: All emails use the application name from the configuration and support both HTML and plain text formats.
Storage Module
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)
User Module
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
AppConfig Interface
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
}EmailConfig Interface
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
- Environment Variables: Store sensitive data in environment variables, not in code
- Firebase Secrets: Use Firebase Secrets Manager for production:
firebase functions:secrets:set EMAIL_PASS - Authentication: All functions require authentication except bootstrap status check
- Role-Based Access: Implement proper role checks in your application
- Password Policies: Enforce strong passwords (min 6 characters)
- Email Verification: Users should verify their email addresses
Development
Build
npm run buildWatch Mode
npm run build:watchTesting
npm testLinting
npm run lintMigration Guide
From Standalone to Shared Library
- Install the shared library in your Firebase functions project
- Update your index.ts to initialize configuration
- Remove duplicate code from your project (bootstrap, email, storage, user modules)
- Update imports to use the shared library
- Configure environment variables according to the template above
- Test thoroughly in emulator before deploying
Example migration:
// 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:
- Make changes in the
firebase/shared/functionsdirectory - Test changes in emulator with one of the consumer projects
- Update version in
package.json - Build and deploy
Troubleshooting
Configuration Not Initialized Error
Error: Application configuration not initialized. Call initializeConfig() first.
Solution: Ensure you call initializeConfig(config) before exporting any functions.
Email Sending Fails
Error: Email configuration incomplete
Solution: Check that all required environment variables are set (EMAIL_HOST, EMAIL_USER, EMAIL_PASS).
Firestore Database Not Found
Error: Firestore database "default" not found
Solution: Either create the database in Firebase Console or set firestoreDatabaseId to undefined to use the default database.
HEIC Conversion Fails
Error: Failed to convert HEIC to JPEG
Solution: Ensure heic-convert and sharp are installed. Check that the file is a valid HEIC image.
License
UNLICENSED - Private library for ZS-Soft/LodgeFlow applications.
Support
For issues or questions, contact the development team or create an issue in the project repository.
