Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -68,44 +68,122 @@ except Exception as e:
|
|
| 68 |
traceback.print_exc()
|
| 69 |
# --- END Firebase Initialization ---
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
users_to_manage = [
|
| 72 |
-
|
| 73 |
-
{"email": "rairorr@gmail.com", "password": "tuna2025!", "display_name": "Rairo", "is_admin": True},
|
| 74 |
{"email": "gwatidzomisheck@gmail.com", "password": "tuna2025!", "display_name": "Gwatidzo Admin", "is_admin": True},
|
| 75 |
-
#
|
| 76 |
-
|
| 77 |
]
|
| 78 |
|
| 79 |
-
|
| 80 |
for user_data in users_to_manage:
|
| 81 |
email = user_data["email"]
|
| 82 |
-
password = user_data["password"]
|
| 83 |
display_name = user_data.get("display_name", email.split('@')[0])
|
| 84 |
-
|
|
|
|
|
|
|
| 85 |
|
| 86 |
try:
|
| 87 |
-
# Attempt to retrieve the user by their email
|
| 88 |
current_user = auth.get_user_by_email(email)
|
| 89 |
-
|
| 90 |
-
except firebase_admin.
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
# --- Helper Functions ---
|
| 111 |
def verify_token(auth_header):
|
|
|
|
| 68 |
traceback.print_exc()
|
| 69 |
# --- END Firebase Initialization ---
|
| 70 |
|
| 71 |
+
|
| 72 |
+
# --- Helper function to ensure user profile in Realtime Database ---
|
| 73 |
+
def ensure_tunasonga_profile_in_rtdb(uid, email, display_name, is_admin_flag):
|
| 74 |
+
"""
|
| 75 |
+
Ensures a user profile exists in Realtime DB for Tunasonga Agri.
|
| 76 |
+
Creates or updates it with the is_admin flag and other defaults.
|
| 77 |
+
"""
|
| 78 |
+
user_ref = db.reference(f'users/{uid}')
|
| 79 |
+
user_data = user_ref.get()
|
| 80 |
+
|
| 81 |
+
if not user_data:
|
| 82 |
+
print(f"Profile for UID {uid} (Email: {email}) not found in RTDB. Creating new profile.")
|
| 83 |
+
new_profile = {
|
| 84 |
+
'email': email,
|
| 85 |
+
'name': display_name,
|
| 86 |
+
'phone_number': "", # Default, can be updated by user
|
| 87 |
+
'location': "", # Default, can be updated by user
|
| 88 |
+
'roles': { # Default roles
|
| 89 |
+
'farmer': False,
|
| 90 |
+
'buyer': False,
|
| 91 |
+
'transporter': False
|
| 92 |
+
},
|
| 93 |
+
'role_applications': {},
|
| 94 |
+
'document_references': {},
|
| 95 |
+
'is_admin': is_admin_flag, # Set based on the script's input
|
| 96 |
+
'is_facilitator': False, # Default
|
| 97 |
+
'created_at': datetime.now(timezone.utc).isoformat(),
|
| 98 |
+
'suspended': False
|
| 99 |
+
}
|
| 100 |
+
try:
|
| 101 |
+
user_ref.set(new_profile)
|
| 102 |
+
print(f"Successfully created RTDB profile for {email} with is_admin: {is_admin_flag}")
|
| 103 |
+
except Exception as e_set:
|
| 104 |
+
print(f"Error setting RTDB profile for {email}: {e_set}")
|
| 105 |
+
else:
|
| 106 |
+
# Profile exists, ensure 'is_admin' flag is correctly set/updated
|
| 107 |
+
if user_data.get('is_admin') != is_admin_flag:
|
| 108 |
+
print(f"Updating is_admin flag for {email} in RTDB to: {is_admin_flag}")
|
| 109 |
+
try:
|
| 110 |
+
user_ref.update({'is_admin': is_admin_flag})
|
| 111 |
+
print(f"Successfully updated is_admin for {email} in RTDB.")
|
| 112 |
+
except Exception as e_update:
|
| 113 |
+
print(f"Error updating is_admin for {email} in RTDB: {e_update}")
|
| 114 |
+
else:
|
| 115 |
+
print(f"RTDB profile for {email} already exists and is_admin is correctly set to: {is_admin_flag}.")
|
| 116 |
+
|
| 117 |
+
# Ensure other essential fields exist if the profile was created by a different process
|
| 118 |
+
# (e.g., if user signed up via app before this script ran)
|
| 119 |
+
updates_needed = {}
|
| 120 |
+
if 'name' not in user_data: updates_needed['name'] = display_name
|
| 121 |
+
if 'roles' not in user_data: updates_needed['roles'] = {'farmer': False, 'buyer': False, 'transporter': False}
|
| 122 |
+
if 'created_at' not in user_data: updates_needed['created_at'] = datetime.now(timezone.utc).isoformat()
|
| 123 |
+
# Add other default fields if necessary
|
| 124 |
+
|
| 125 |
+
if updates_needed:
|
| 126 |
+
print(f"Ensuring essential fields for existing profile of {email} in RTDB.")
|
| 127 |
+
try:
|
| 128 |
+
user_ref.update(updates_needed)
|
| 129 |
+
print(f"Successfully updated essential fields for {email} in RTDB.")
|
| 130 |
+
except Exception as e_essential_update:
|
| 131 |
+
print(f"Error updating essential fields for {email} in RTDB: {e_essential_update}")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# --- User Management Logic ---
|
| 135 |
users_to_manage = [
|
| 136 |
+
{"email": "rairorr@gmail.com", "password": "tuna2025!", "display_name": "Rairo Admin", "is_admin": True},
|
|
|
|
| 137 |
{"email": "gwatidzomisheck@gmail.com", "password": "tuna2025!", "display_name": "Gwatidzo Admin", "is_admin": True},
|
| 138 |
+
# Add other users here if needed, e.g., to remove admin status from a previous admin
|
| 139 |
+
# {"email": "oldadmin@example.com", "password": "somepassword", "display_name": "Old Admin", "is_admin": False},
|
| 140 |
]
|
| 141 |
|
| 142 |
+
print("\n--- Starting User and Admin Claim Management ---")
|
| 143 |
for user_data in users_to_manage:
|
| 144 |
email = user_data["email"]
|
| 145 |
+
password = user_data["password"] # Password is only used if creating a new Auth user
|
| 146 |
display_name = user_data.get("display_name", email.split('@')[0])
|
| 147 |
+
is_admin_flag_for_script = user_data.get("is_admin", False) # Renamed to avoid conflict
|
| 148 |
+
|
| 149 |
+
print(f"\nProcessing user: {email} (Target admin status: {is_admin_flag_for_script})")
|
| 150 |
|
| 151 |
try:
|
|
|
|
| 152 |
current_user = auth.get_user_by_email(email)
|
| 153 |
+
print(f"Firebase Auth: User {email} (UID: {current_user.uid}) already exists.")
|
| 154 |
+
except firebase_admin.auth.UserNotFoundError: # Corrected exception type
|
| 155 |
+
print(f"Firebase Auth: User {email} not found. Creating new user...")
|
| 156 |
+
try:
|
| 157 |
+
current_user = auth.create_user(
|
| 158 |
+
email=email,
|
| 159 |
+
email_verified=True, # You can set this as needed
|
| 160 |
+
password=password,
|
| 161 |
+
display_name=display_name
|
| 162 |
+
)
|
| 163 |
+
print(f"Firebase Auth: Created new user {email} (UID: {current_user.uid})")
|
| 164 |
+
except Exception as e_create:
|
| 165 |
+
print(f"Firebase Auth: Error creating user {email}: {e_create}")
|
| 166 |
+
continue # Skip to the next user if creation fails
|
| 167 |
+
|
| 168 |
+
# Set or unset custom user claims for Firebase Auth
|
| 169 |
+
current_claims = current_user.custom_claims or {}
|
| 170 |
+
if is_admin_flag_for_script:
|
| 171 |
+
if not current_claims.get("admin"):
|
| 172 |
+
auth.set_custom_user_claims(current_user.uid, {"admin": True})
|
| 173 |
+
print(f"Firebase Auth: Set admin custom claim for {email}.")
|
| 174 |
+
else:
|
| 175 |
+
print(f"Firebase Auth: Admin custom claim already set for {email}.")
|
| 176 |
+
else: # is_admin_flag_for_script is False
|
| 177 |
+
if current_claims.get("admin"):
|
| 178 |
+
auth.set_custom_user_claims(current_user.uid, {}) # Remove admin claim
|
| 179 |
+
print(f"Firebase Auth: Removed admin custom claim for {email}.")
|
| 180 |
+
else:
|
| 181 |
+
print(f"Firebase Auth: Admin custom claim already not set (or removed) for {email}.")
|
| 182 |
+
|
| 183 |
+
# Ensure/Update profile in Realtime Database
|
| 184 |
+
ensure_tunasonga_profile_in_rtdb(current_user.uid, email, display_name, is_admin_flag_for_script)
|
| 185 |
+
|
| 186 |
+
print("\n--- User and Admin Claim Management Complete ---")
|
| 187 |
|
| 188 |
# --- Helper Functions ---
|
| 189 |
def verify_token(auth_header):
|