File size: 1,457 Bytes
45742a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69117e1
 
 
 
 
 
 
45742a7
 
69117e1
45742a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Database connection module for MongoDB.
Uses motor (async MongoDB driver) for FastAPI compatibility.
"""
import os
from dotenv import load_dotenv
from motor.motor_asyncio import AsyncIOMotorClient

# Load environment variables from .env file
load_dotenv()

# MongoDB connection settings from environment
MONGODB_URI = os.getenv("MONGODB_URI", "mongodb://localhost:27017")
DATABASE_NAME = os.getenv("DATABASE_NAME", "deepfake_detector")

# Global client and database references
client = None
db = None


async def connect_to_mongo():
    """Connect to MongoDB on startup."""
    global client, db
    print(f"Connecting to MongoDB...")
    client = AsyncIOMotorClient(MONGODB_URI)
    db = client[DATABASE_NAME]
    
    # Drop old indexes that may cause conflicts
    try:
        await db.users.drop_index("api_key_1")
        print("Dropped old api_key index.")
    except Exception:
        pass  # Index doesn't exist, that's fine
    
    # Create indexes for faster lookups
    await db.users.create_index("email", unique=True)
    await db.users.create_index("api_key_hash", unique=True)  # Changed from api_key
    
    print(f"MongoDB connected successfully to database: {DATABASE_NAME}")


async def close_mongo_connection():
    """Close MongoDB connection on shutdown."""
    global client
    if client:
        client.close()
        print("MongoDB connection closed.")


def get_database():
    """Get database instance."""
    return db