File size: 2,479 Bytes
97b7267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9cb4b
 
86eaec7
97b7267
86eaec7
97b7267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from dotenv import load_dotenv
import firebase_admin
from firebase_admin import credentials, auth as firebase_auth
from pymongo import MongoClient
from bson.binary import Binary
import json

load_dotenv()

# cred_path = os.getenv("FIREBASE_ADMIN_KEY")
# if not cred_path:
#     raise ValueError("FIREBASE_ADMIN_KEY chưa được khai báo trong .env hoặc đường dẫn bị sai!")
# if not firebase_admin._apps:
#     cred = credentials.Certificate(cred_path)
#     firebase_admin.initialize_app(cred)

firebase_admin_json = os.getenv("FIREBASE_ADMIN_JSON")
if firebase_admin_json:
    import tempfile
    service_account_path = os.path.join(tempfile.gettempdir(), "serviceAccountKey.json")
    with open(service_account_path, "w") as f:
        f.write(firebase_admin_json)
    cred_path = service_account_path
else:
    cred_path = os.getenv("FIREBASE_ADMIN_KEY")
    
if not cred_path:
    raise ValueError("FIREBASE_ADMIN_KEY chưa được khai báo trong .env hoặc đường dẫn bị sai!")
if not firebase_admin._apps:
    cred = credentials.Certificate(cred_path)
    firebase_admin.initialize_app(cred)

mongo_uri = os.getenv("MONGO_URI")
mongo_dbname = os.getenv("MONGO_DBNAME")


def get_mongo_collection():
    client = MongoClient(mongo_uri)
    db = client[mongo_dbname]
    return db["users"]


def verify_firebase_token(id_token):
    try:
        decoded = firebase_auth.verify_id_token(id_token)
        return decoded
    except Exception as e:
        print("Token verify fail:", e)
        return None


def register_user_to_mongo(uid, email, user_name):
    users = get_mongo_collection()
    
    if not users.find_one({"uid": uid}):
        print("Registering new user:", uid, email, user_name)
        users.insert_one({"uid": uid, "email": email, "user_name": user_name})
    return True


def save_avatar(uid, file_bytes):
    users = get_mongo_collection()
    users.update_one(
        {"uid": uid}, {"$set": {"avatar_blob": Binary(file_bytes)}}, upsert=True
    )


def get_avatar_blob(uid):
    users = get_mongo_collection()
    user = users.find_one({"uid": uid}, {"avatar_blob": 1})
    return user.get("avatar_blob") if user and "avatar_blob" in user else None


def get_user_profile(uid):
    users = get_mongo_collection()
    return users.find_one({"uid": uid})


def update_username_in_mongo(uid, new_username):
    users = get_mongo_collection()
    users.update_one({"uid": uid}, {"$set": {"user_name": new_username}})