""" Simple login debugging script for HealthGuard-AI. This script will help diagnose what's happening during the login process. """ import os import sys import traceback from dotenv import load_dotenv # Load environment variables load_dotenv() def test_environment(): """Test environment configuration.""" print("=== Environment Configuration Test ===") print(f"SECRET_KEY set: {'Yes' if os.getenv('SECRET_KEY') else 'No'}") print(f"MONGODB_URI set: {'Yes' if os.getenv('MONGODB_URI') else 'No'}") print(f"Current working directory: {os.getcwd()}") print() def test_imports(): """Test if all required modules can be imported.""" print("=== Import Test ===") try: import flask print(f"✓ Flask: {flask.__version__}") except Exception as e: print(f"✗ Flask import failed: {e}") return False try: import bcrypt print("✓ bcrypt imported successfully") except Exception as e: print(f"✗ bcrypt import failed: {e}") return False try: import pymongo print("✓ pymongo imported successfully") except Exception as e: print(f"✗ pymongo import failed: {e}") return False print() return True def test_database_connection(): """Test database connection.""" print("=== Database Connection Test ===") try: MONGODB_URI = os.getenv('MONGODB_URI') if not MONGODB_URI: print("⚠ MONGODB_URI not set in environment variables") return False import pymongo from pymongo.errors import ServerSelectionTimeoutError # Try to connect with a short timeout client = pymongo.MongoClient(MONGODB_URI, serverSelectionTimeoutMS=5000) client.admin.command('ping') print("✓ Database connection successful") # Try to access the database db_name = os.getenv('MONGODB_DB', 'healthcare_db') db = client[db_name] print(f"✓ Database '{db_name}' accessible") # Try to access users collection users_collection = db['users'] count = users_collection.count_documents({}) print(f"✓ Users collection accessible, contains {count} documents") client.close() return True except ServerSelectionTimeoutError: print("✗ Database connection failed: Server selection timeout") return False except Exception as e: print(f"✗ Database connection failed: {e}") traceback.print_exc() return False finally: print() def test_bcrypt_functionality(): """Test bcrypt functionality.""" print("=== Bcrypt Functionality Test ===") try: import bcrypt # Test password hashing password = "testpassword123" hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) print("✓ Password hashing works") # Test password verification if bcrypt.checkpw(password.encode('utf-8'), hashed): print("✓ Password verification works") else: print("✗ Password verification failed") return False return True except Exception as e: print(f"✗ Bcrypt functionality failed: {e}") traceback.print_exc() return False finally: print() def simulate_login(email, password): """Simulate the login process.""" print("=== Login Simulation ===") print(f"Attempting login for: {email}") try: # Import the app and mongo from app import mongo if mongo.cx is None: print("✗ Database connection not available") return False # Find user in database print("Looking for user in database...") user = mongo.db.users.find_one({'email': email}) if not user: print(f"✗ User with email '{email}' not found") return False print(f"✓ User found: {user['name']} ({user['role']})") # Check password print("Verifying password...") if bcrypt.checkpw(password.encode('utf-8'), user['password']): print("✓ Password verified successfully") print("Login would be successful!") return True else: print("✗ Password verification failed") return False except Exception as e: print(f"✗ Login simulation failed: {e}") traceback.print_exc() return False finally: print() def main(): """Main function.""" print("HealthGuard-AI Login Debug Tool") print("=" * 40) print() # Run all tests test_environment() if not test_imports(): print("Critical import failed. Cannot continue.") return test_database_connection() test_bcrypt_functionality() # Ask user if they want to simulate a login print("Do you want to simulate a login? (y/n): ", end="") choice = input().strip().lower() if choice == 'y': email = input("Enter email: ").strip() password = input("Enter password: ").strip() simulate_login(email, password) if __name__ == "__main__": main()