File size: 1,735 Bytes
24e6f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from bson import ObjectId
from expense_tracker.utils import MongoDBClient
from users.mongo_auth import MongoUser
from datetime import datetime

def get_user_db_id(user):
    """
    Returns the valid MongoDB ObjectId for a given user.
    - If user is a MongoUser (from App Login), returns its _id directly.
    - If user is a Django User (from Admin Login), finds or creates a corresponding
      MongoDB document based on email/username and returns that _id.
    """
    # Case 1: Already a MongoUser (has hex string id)
    if isinstance(user, MongoUser):
        return ObjectId(user.id)
        
    # Case 2: Django User (Integer ID) -> Logic to Sync/Find in Mongo
    # We assume 'user' is a standard Django User model instance
    db = MongoDBClient.get_client()
    
    # 1. Try finding by Email (most reliable link)
    mongo_user = db.users.find_one({'email': user.email})
    
    # 2. If not found by email, try username
    if not mongo_user:
        mongo_user = db.users.find_one({'username': user.username})
        
    # 3. If still not found, create a new Mongo Doc for this Admin
    if not mongo_user:
        new_doc = {
            'username': user.username,
            'email': user.email,
            'password': 'SyncedFromSQLite', # Placeholder, auth is handled by SQLite
            'is_active': user.is_active,
            'is_staff': user.is_staff,
            'is_superuser': user.is_superuser,
            'date_joined': datetime.now(),
            'financial_data': {
                'incomes': [],
                'expenses': []
            },
            'budgets': []
        }
        result = db.users.insert_one(new_doc)
        return result.inserted_id
        
    return mongo_user['_id']