HealthGuard-AI / login_debug.py
kalyan9's picture
Upload 14 files
95e10ab verified
Raw History Blame Contribute Delete
5.55 kB
"""
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()