# Authentication Debug Setup Guide This guide explains the `auth-debug-setup.ts` file and how to use it for debugging authentication flows in the Medication Reminder application. ## Overview The `auth-debug-setup.ts` file is a Playwright global setup script specifically designed for debugging authentication-related issues. It ensures that all required services are running and properly configured before running authentication tests. ## What It Does ### 🔧 Service Initialization - **Frontend Service**: Verifies the app is running on `http://localhost:8080` - **CouchDB Database**: Ensures CouchDB is accessible on `http://localhost:5984` - **Database Setup**: Creates necessary databases if they don't exist - **Admin User Verification**: Tests admin login functionality end-to-end ### 📊 Diagnostics - **Service Health Checks**: Comprehensive connectivity testing - **Database Status**: Lists available databases and connection status - **Environment Information**: Logs Node.js version, platform, and environment variables - **Network Connectivity**: Tests various endpoints for accessibility ## File Structure ```typescript // Main setup functions globalSetup(); // Orchestrates all setup tasks waitForServices(); // Waits for services to be ready initializeTestData(); // Creates required databases verifyAdminUser(); // Tests admin login flow logEnvironmentInfo(); // Logs debugging information // Diagnostic utilities runServiceDiagnostics(); // Comprehensive service testing testDatabaseConnectivity(); // Detailed database status ``` ## Configuration ### Required Services Before running auth debug tests, ensure these services are running: 1. **Frontend Application** ```bash bun run dev # Runs on http://localhost:8080 ``` 2. **CouchDB Database** ```bash docker-compose -f docker/docker-compose.yaml up -d # Runs on http://localhost:5984 ``` ### Environment Variables The setup respects these environment variables: - `NODE_ENV`: Environment mode (development/test/production) - `CI`: CI/CD environment flag - `DEBUG_MODE`: Enables additional debugging features ### Database Configuration The setup creates these databases automatically: - `users` - User accounts and authentication data - `medications` - Medication information - `settings` - Application settings - `taken_doses` - Medication intake records - `reminders` - Reminder configurations ### Default Credentials The setup uses these default credentials for testing: - **CouchDB**: `admin:password` - **Test Admin User**: `admin@localhost:admin123!` ## Usage ### Running Auth Debug Tests ```bash # Run auth debug tests specifically bunx playwright test --config=tests/e2e/playwright.auth.config.ts # Run with UI for interactive debugging bunx playwright test --config=tests/e2e/playwright.auth.config.ts --ui # Run in debug mode bunx playwright test --config=tests/e2e/playwright.auth.config.ts --debug ``` ### Manual Setup Verification You can verify the setup manually: ```bash # Check frontend curl http://localhost:8080 # Check CouchDB curl -u admin:password http://localhost:5984 # List databases curl -u admin:password http://localhost:5984/_all_dbs ``` ## Troubleshooting ### Common Issues #### 1. Services Not Ready **Symptoms**: Setup fails with service connection errors **Solutions**: ```bash # Check if services are running docker ps netstat -tlnp | grep 8080 netstat -tlnp | grep 5984 # Restart services docker-compose -f docker/docker-compose.yaml restart bun run dev ``` #### 2. Database Connection Failed **Symptoms**: CouchDB authentication or connection errors **Solutions**: ```bash # Check CouchDB logs docker-compose -f docker/docker-compose.yaml logs couchdb # Reset CouchDB data docker-compose -f docker/docker-compose.yaml down -v docker-compose -f docker/docker-compose.yaml up -d ``` #### 3. Admin User Not Found **Symptoms**: Admin login verification fails **Solutions**: - Check if admin user exists in the users database - Verify credentials match the expected format - Create admin user manually if needed #### 4. Timeout Issues **Symptoms**: Setup times out waiting for services **Solutions**: ```bash # Increase timeout values in setup # Check system resources free -h docker stats # Reduce parallel processes pkill -f "node.*vite" pkill -f "playwright" ``` ### Debug Logs The setup provides detailed logging at different levels: ```typescript // Enable debug logging logger.setLevel(LogLevel.DEBUG); // View specific context logs logger.getLogs('SETUP'); logger.getLogs('AUTH'); logger.getLogs('DATABASE'); ``` ### Diagnostic Output The setup generates comprehensive diagnostic information: ``` 🌍 Environment Information: Node.js: v18.17.0 Platform: linux NODE_ENV: test CI: false Frontend URL: http://localhost:8080 CouchDB URL: http://localhost:5984 🔍 Running comprehensive service diagnostics... Frontend status: 200 OK Database connected with 5 databases Health endpoint accessible ✅ Auth debug setup completed in 2847ms ``` ## Integration with Test Suite ### Playwright Configuration The setup integrates with `playwright.auth.config.ts`: ```typescript export default defineConfig({ globalSetup: require.resolve('./auth-debug-setup.ts'), globalTeardown: require.resolve('./auth-debug-teardown.ts'), // ... other config }); ``` ### Test Dependencies Tests that depend on this setup: - `auth-debug.spec.ts` - Main authentication validation tests - `admin.spec.ts` - Admin functionality tests - `auth.spec.ts` - General authentication tests ## Best Practices ### 1. Environment Isolation - Use dedicated test databases - Clean up test data between runs - Avoid production credentials ### 2. Robust Error Handling - Don't fail setup for non-critical issues - Log warnings for optional features - Provide helpful error messages ### 3. Service Dependencies - Wait for all required services - Test actual connectivity, not just port availability - Verify service functionality, not just status ### 4. Debugging Support - Comprehensive logging at appropriate levels - Detailed diagnostic information - Clear failure messages with next steps ## Development ### Modifying the Setup When modifying the setup script: 1. **Test thoroughly** in different environments 2. **Maintain backward compatibility** with existing tests 3. **Update documentation** for any new features 4. **Add appropriate logging** for debugging ### Adding New Services To add new service checks: ```typescript // Add to waitForServices() await waitForService('http://localhost:9000', 'NewService'); // Add diagnostic check async function checkNewService() { // Implementation } ``` ### Environment-Specific Configuration For different environments: ```typescript const config = { development: { timeout: 60000, retries: 3, }, ci: { timeout: 120000, retries: 5, }, }; ``` ## Related Files - `auth-debug-teardown.ts` - Cleanup and reporting - `auth-debug.spec.ts` - Main authentication tests - `playwright.auth.config.ts` - Playwright configuration - `AUTH-DEBUG-GUIDE.md` - Test execution guide ## Support For issues with the auth debug setup: 1. Check the diagnostic output for specific error messages 2. Verify all required services are running 3. Review the troubleshooting section above 4. Check related test files for configuration examples 5. Enable debug logging for detailed information The setup is designed to be self-diagnosing and should provide clear information about any issues encountered during initialization.