Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -181,10 +181,6 @@ def send_rotation_notification(job_id, shift_record):
|
|
| 181 |
except Exception as e:
|
| 182 |
logger.error(f"Error sending rotation notification for job {job_id}: {e}")
|
| 183 |
|
| 184 |
-
# === Auth Middleware ===
|
| 185 |
-
# Add this import at the top if not already there
|
| 186 |
-
# from firebase_admin import auth as firebase_auth # Already imported
|
| 187 |
-
|
| 188 |
# === Auth Middleware ===
|
| 189 |
def verify_token(req):
|
| 190 |
"""
|
|
@@ -192,8 +188,12 @@ def verify_token(req):
|
|
| 192 |
Automatically creates admin entry in DB if email is in ADMIN_EMAILS but UID is not found.
|
| 193 |
Returns decoded token dict if valid admin, None otherwise.
|
| 194 |
"""
|
|
|
|
|
|
|
|
|
|
| 195 |
auth_header = req.headers.get("Authorization")
|
| 196 |
if not auth_header:
|
|
|
|
| 197 |
return None
|
| 198 |
|
| 199 |
try:
|
|
@@ -205,10 +205,12 @@ def verify_token(req):
|
|
| 205 |
|
| 206 |
# Verify the token
|
| 207 |
decoded = firebase_auth.verify_id_token(token)
|
|
|
|
| 208 |
|
| 209 |
# Get user UID and email from decoded token
|
| 210 |
uid = decoded.get('uid')
|
| 211 |
-
email = decoded.get('email')
|
|
|
|
| 212 |
|
| 213 |
if not uid:
|
| 214 |
logger.error("Verified token does not contain a UID.")
|
|
@@ -217,10 +219,11 @@ def verify_token(req):
|
|
| 217 |
# Check if user is admin by querying Firebase Realtime Database using UID
|
| 218 |
admins_ref = db.reference("/admins")
|
| 219 |
admin_data = admins_ref.child(uid).get()
|
|
|
|
| 220 |
|
| 221 |
if admin_data and admin_data.get("is_admin", False):
|
| 222 |
# User is already an admin in the database
|
| 223 |
-
logger.info(f"User {uid} ({email}) is authorized as admin.")
|
| 224 |
return decoded
|
| 225 |
|
| 226 |
elif email and email in ADMIN_EMAILS:
|
|
@@ -228,18 +231,25 @@ def verify_token(req):
|
|
| 228 |
# This is likely their first time accessing the API.
|
| 229 |
# Automatically create their admin entry using their UID.
|
| 230 |
logger.info(f"First time admin access for {email} (UID: {uid}). Creating database entry.")
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
else:
|
| 241 |
-
# User is not in the approved admin list
|
| 242 |
-
logger.warning(f"User {uid} ({email}) is not in the approved admin list or not found
|
| 243 |
return None
|
| 244 |
|
| 245 |
except firebase_auth.InvalidIdTokenError as e:
|
|
@@ -252,10 +262,9 @@ def verify_token(req):
|
|
| 252 |
logger.error(f"Firebase ID token has been revoked: {e}")
|
| 253 |
return None
|
| 254 |
except Exception as e:
|
| 255 |
-
logger.error(f"Unexpected error during token verification: {e}")
|
| 256 |
return None
|
| 257 |
|
| 258 |
-
|
| 259 |
# === Admin Setup (Legacy - kept for compatibility) ===
|
| 260 |
def setup_admins():
|
| 261 |
ref = db.reference("admins")
|
|
|
|
| 181 |
except Exception as e:
|
| 182 |
logger.error(f"Error sending rotation notification for job {job_id}: {e}")
|
| 183 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
# === Auth Middleware ===
|
| 185 |
def verify_token(req):
|
| 186 |
"""
|
|
|
|
| 188 |
Automatically creates admin entry in DB if email is in ADMIN_EMAILS but UID is not found.
|
| 189 |
Returns decoded token dict if valid admin, None otherwise.
|
| 190 |
"""
|
| 191 |
+
# Use the logger instance created in your full script
|
| 192 |
+
logger = logging.getLogger('guards_api')
|
| 193 |
+
|
| 194 |
auth_header = req.headers.get("Authorization")
|
| 195 |
if not auth_header:
|
| 196 |
+
logger.warning("Authorization header missing.")
|
| 197 |
return None
|
| 198 |
|
| 199 |
try:
|
|
|
|
| 205 |
|
| 206 |
# Verify the token
|
| 207 |
decoded = firebase_auth.verify_id_token(token)
|
| 208 |
+
logger.debug(f"Token verified successfully. Decoded token keys: {list(decoded.keys())}")
|
| 209 |
|
| 210 |
# Get user UID and email from decoded token
|
| 211 |
uid = decoded.get('uid')
|
| 212 |
+
email = decoded.get('email') # This should be present in the token
|
| 213 |
+
logger.debug(f"Extracted UID: {uid}, Email: {email}")
|
| 214 |
|
| 215 |
if not uid:
|
| 216 |
logger.error("Verified token does not contain a UID.")
|
|
|
|
| 219 |
# Check if user is admin by querying Firebase Realtime Database using UID
|
| 220 |
admins_ref = db.reference("/admins")
|
| 221 |
admin_data = admins_ref.child(uid).get()
|
| 222 |
+
logger.debug(f"Admin data retrieved for UID {uid}: {admin_data}")
|
| 223 |
|
| 224 |
if admin_data and admin_data.get("is_admin", False):
|
| 225 |
# User is already an admin in the database
|
| 226 |
+
logger.info(f"User {uid} ({email}) is authorized as admin (found in DB).")
|
| 227 |
return decoded
|
| 228 |
|
| 229 |
elif email and email in ADMIN_EMAILS:
|
|
|
|
| 231 |
# This is likely their first time accessing the API.
|
| 232 |
# Automatically create their admin entry using their UID.
|
| 233 |
logger.info(f"First time admin access for {email} (UID: {uid}). Creating database entry.")
|
| 234 |
+
try:
|
| 235 |
+
admins_ref.child(uid).set({
|
| 236 |
+
"email": email,
|
| 237 |
+
"is_admin": True
|
| 238 |
+
# Removed first_seen to keep it simple like original, add back if needed
|
| 239 |
+
})
|
| 240 |
+
logger.info(f"Admin entry created for UID {uid}.")
|
| 241 |
+
# Return the decoded token as they are now an admin
|
| 242 |
+
return decoded
|
| 243 |
+
except Exception as db_error:
|
| 244 |
+
logger.error(f"Failed to create admin entry for UID {uid} in database: {db_error}")
|
| 245 |
+
# Even if DB write fails, if they are in ADMIN_EMAILS, we could consider them authorized
|
| 246 |
+
# but it's safer to deny access if we can't record it.
|
| 247 |
+
# Alternatively: return decoded (less safe) or return None (safer)
|
| 248 |
+
return None
|
| 249 |
|
| 250 |
else:
|
| 251 |
+
# User is not in the approved admin list or email not found in token
|
| 252 |
+
logger.warning(f"User {uid} ({email}) is not in the approved admin list or email not found.")
|
| 253 |
return None
|
| 254 |
|
| 255 |
except firebase_auth.InvalidIdTokenError as e:
|
|
|
|
| 262 |
logger.error(f"Firebase ID token has been revoked: {e}")
|
| 263 |
return None
|
| 264 |
except Exception as e:
|
| 265 |
+
logger.error(f"Unexpected error during token verification: {e}", exc_info=True) # exc_info logs the full traceback
|
| 266 |
return None
|
| 267 |
|
|
|
|
| 268 |
# === Admin Setup (Legacy - kept for compatibility) ===
|
| 269 |
def setup_admins():
|
| 270 |
ref = db.reference("admins")
|