# Firebase Authentication Automation with Terraform This guide explains how Firebase Authentication settings are automated in the Rothbard Law Group deployment. ## 🚀 What's Automated ### 1. Authentication Providers - **Email/Password**: Enabled by default - **Google Sign-In**: Optional (controlled by `enable_google_signin` variable) - **Phone, Facebook, Apple**: Disabled for security ### 2. Email Templates - **Password Reset**: Professional HTML and text templates - **Email Verification**: Welcome templates with branding - **Customizable**: From address, name, and reply-to settings ### 3. Security Rules - **Firestore Rules**: Users can only access their own data - **Authentication Required**: All database operations require auth - **Profile Access**: Users can read/write their own profile only ### 4. Firebase Hosting - **Static Asset Hosting**: Optional for CSS, JS, images - **Caching Headers**: Optimized performance - **URL Rewrites**: Proper routing for SPA ## 📋 Configuration Variables Add these to your `terraform.tfvars`: ```hcl # Authentication Settings enable_google_signin = false # Set to true to enable Google Sign-In # Email Configuration auth_from_email = "noreply@rothbardlaw.com" auth_from_name = "Rothbard Law Group" auth_reply_to = "support@rothbardlaw.com" ``` ## 🔧 Authentication Provider Setup ### Email/Password (Default) ```hcl sign_in_options { email { enabled = true password_required = true } } ``` ### Google Sign-In (Optional) To enable Google Sign-In: 1. **Set variable**: ```hcl enable_google_signin = true ``` 2. **Configure OAuth in Google Cloud**: ```bash # Enable Google+ API gcloud services enable plus.googleapis.com # Create OAuth consent screen gcloud alpha iap oauth-clients create \ --display-name="Rothbard Portal" \ --brand="Rothbard Law Group" ``` 3. **Update Firebase Console**: - Go to Firebase Console → Authentication → Sign-in method - Enable Google provider - Add your OAuth client ID and secret ## 📧 Email Template Customization ### Template Files - `templates/reset_password.html` - Password reset HTML - `templates/reset_password.txt` - Password reset text - `templates/email_verification.html` - Email verification HTML - `templates/email_verification.txt` - Email verification text ### Customization Options - **Branding**: Update colors, logos in HTML templates - **Contact Info**: Change address, phone numbers - **Content**: Modify welcome messages and instructions ### Email Variables Available - `{{ resetLink }}` - Password reset URL - `{{ verificationLink }}` - Email verification URL - `{{ userEmail }}` - User's email address ## 🔒 Security Rules Explained ### Firestore Rules ```javascript // Users can only access their own profile match /users/{userId} { allow read, write: if request.auth.uid == userId; } // All other collections require authentication match /{collection=**} { allow read, write: if request.auth != null; } ``` ### Security Features - **User Isolation**: Users can't access other users' data - **Authentication Required**: No anonymous access - **Self-Service**: Users can only modify their own profiles ## 🛠️ Advanced Configuration ### Multi-Factor Authentication Currently disabled for simplicity. To enable: ```hcl multi_factor_auth { enabled = true provider_configs { phone { enabled = true } } } ``` ### Custom Email Templates For more advanced templates, you can use Firebase Admin SDK: ```python # In your Flask app from firebase_admin import auth def send_custom_email(user_email, template_name): # Custom email sending logic pass ``` ### Domain Restrictions To restrict authentication to specific domains: ```javascript // In Firebase Auth security rules rules_version = '2'; service cloud.firestore { match /users/{userId} { allow read, write: if request.auth != null && request.auth.token.email.matches('.*@rothbardlaw\\.com$'); } } ``` ## 📊 Monitoring and Analytics ### Authentication Events Track these events in your application: ```python # Log authentication events def log_auth_event(event_type, user_id, details=None): db.collection('auth_logs').add({ 'event_type': event_type, 'user_id': user_id, 'timestamp': firestore.SERVER_TIMESTAMP, 'details': details or {} }) ``` ### Key Events to Monitor - User registrations - Password resets - Failed login attempts - Email verifications ## 🔄 Updates and Maintenance ### Updating Email Templates 1. Edit template files in `terraform/templates/` 2. Run `terraform apply` to update 3. Changes apply to new emails immediately ### Adding New Providers 1. Update `google_identitytoolkit_config` in `main.tf` 2. Add provider-specific variables 3. Configure OAuth credentials in Google Cloud 4. Apply Terraform changes ### Security Rule Updates 1. Modify `google_firestore_security_policy` in `main.tf` 2. Test rules in Firebase Console first 3. Apply with Terraform ## 🚨 Troubleshooting ### Common Issues 1. **Email Templates Not Working** - Check template file paths - Verify template syntax - Check email provider settings 2. **Authentication Provider Not Working** - Verify API credentials - Check provider configuration - Review Firebase Console settings 3. **Security Rules Blocking Access** - Test rules in Firebase Console - Check user authentication status - Verify collection/document paths ### Debug Commands ```bash # Check Firebase Auth configuration gcloud auth troubleshoot # Test authentication flow curl -X POST "https://identitytoolkit.googleapis.com/v1/accounts:signIn?key=YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"email":"user@example.com","password":"password","returnSecureToken":true}' # Check Firestore rules gcloud firestore databases rules describe \ --project=your-project-id ``` ## 📚 Additional Resources - [Firebase Authentication Documentation](https://firebase.google.com/docs/auth) - [Terraform Google Provider](https://registry.terraform.io/providers/hashicorp/google/latest/docs) - [Firestore Security Rules](https://firebase.google.com/docs/firestore/security/get-started) - [Firebase Email Templates](https://firebase.google.com/docs/auth/custom-email-templates) ## 🎯 Best Practices 1. **Security First** - Use HTTPS everywhere - Implement proper session management - Regular security audits 2. **User Experience** - Clear error messages - Professional email templates - Mobile-responsive design 3. **Maintenance** - Regular backups - Monitoring and alerts - Documentation updates 4. **Compliance** - GDPR compliance for EU users - Data retention policies - Privacy policy alignment This automation ensures your Firebase Authentication is secure, professional, and maintainable while following industry best practices for legal client portals.