File size: 5,548 Bytes
95e10ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""

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()