semblance-dev/backend/app/db.py
2025-08-04 09:07:59 -05:00

67 lines
No EOL
3.2 KiB
Python

from pymongo import MongoClient
import os
import logging
# MongoDB connection
def get_db():
# Try to read environment variables for MongoDB credentials
mongo_user = os.environ.get('MONGO_USER')
mongo_pass = os.environ.get('MONGO_PASS')
mongo_host = os.environ.get('MONGO_HOST', 'localhost')
mongo_port = os.environ.get('MONGO_PORT', '27017')
# Try with standard credentials first
standard_credentials = [
{"user": "admin", "pass": "admin", "db": "admin"},
{"user": "mongodb", "pass": "mongodb", "db": "admin"},
{"user": "root", "pass": "root", "db": "admin"},
{"user": "user", "pass": "pass", "db": "admin"}
]
# Try each set of standard credentials
for creds in standard_credentials:
try:
uri = f"mongodb://{creds['user']}:{creds['pass']}@{mongo_host}:{mongo_port}/semblance_db?authSource={creds['db']}"
client = MongoClient(uri, serverSelectionTimeoutMS=2000)
db = client.semblance_db
# Test the connection with a simple command
db.command('ping')
logging.debug(f"Successfully connected to MongoDB with standard credentials ({creds['user']})")
return db
except Exception as e:
# Continue trying other credentials
pass
# Try to connect without authentication if standard credentials don't work
try:
client = MongoClient(f'mongodb://{mongo_host}:{mongo_port}', serverSelectionTimeoutMS=5000)
# Simply use the database as is - MongoDB will allow this if auth is not required
db = client.semblance_db
# Test the connection with a simple command
db.command('ping')
# Try a write operation to verify we have proper access
test_result = db.test_collection.insert_one({"test": "auth_test"})
db.test_collection.delete_one({"_id": test_result.inserted_id})
logging.debug("Successfully connected to MongoDB without authentication")
return db
except Exception as e:
logging.debug(f"Could not connect without auth: {e}")
# If we get here, we need authentication - try with environment vars if provided
if mongo_user and mongo_pass:
try:
uri = f"mongodb://{mongo_user}:{mongo_pass}@{mongo_host}:{mongo_port}/semblance_db?authSource=admin"
client = MongoClient(uri, serverSelectionTimeoutMS=5000)
db = client.semblance_db
db.command('ping') # Test the connection
logging.debug(f"Successfully connected to MongoDB with credentials for user: {mongo_user}")
return db
except Exception as e:
logging.warning(f"Failed to connect with environment credentials: {e}")
# Last resort - log warning and return client that will fail later if DB actually needs auth
logging.warning("Could not authenticate with MongoDB. If authentication is required, operations will fail.")
logging.warning("To fix this: Set MONGO_USER and MONGO_PASS environment variables.")
# Return a client that will likely fail when operations are performed, but the app will start
client = MongoClient(f'mongodb://{mongo_host}:{mongo_port}', serverSelectionTimeoutMS=5000)
return client.semblance_db