""" ALLI Backend - Admin Users & Email Whitelist Repository Mixin Maintains authorized admin emails in MongoDB Atlas and validates platform admin access. """ import os from typing import Any, Dict, List, Optional from database.connection import get_utc_now DEFAULT_DEV_ADMIN_EMAILS = frozenset({ "admin@alli.io", "owner@alli.io", "developer@alli.io", "narayanansubramani14@gmail.com", }) class AdminRepoMixin: """Admin email whitelist and privileges repository operations.""" def _init_admin_store(self) -> None: self._admin_emails_store: Dict[str, Dict[str, Any]] = {} now = get_utc_now() for e in DEFAULT_DEV_ADMIN_EMAILS: self._admin_emails_store[e] = { "email": e, "role": "admin", "status": "active", "added_at": now, "added_by": "system_bootstrap", } def is_admin_email(self, email: Optional[str]) -> bool: """Check if an email is registered as an active platform administrator in MongoDB.""" if not email or not isinstance(email, str): return False normalized = email.strip().lower() if not normalized: return False # 1. Environment variable configuration override env_admins = { e.strip().lower() for e in os.environ.get("ADMIN_EMAILS", "").split(",") if e.strip() } if normalized in env_admins: return True # 2. Query MongoDB 'admin_emails' collection col = self.get_collection("admin_emails") if col is not None: try: doc = col.find_one({"email": normalized, "status": {"$ne": "disabled"}}, {"_id": 0}) if doc: return True except Exception as ex: print(f"[ALLI MongoDB] Admin email lookup error: {ex}") # 3. Query MongoDB 'users' collection for admin / owner role if self.is_connected and self.users_collection is not None: try: user_doc = self.users_collection.find_one( {"email": normalized, "role": {"$in": ["admin", "owner", "service_role"]}}, {"_id": 0} ) if user_doc: return True except Exception as ex: print(f"[ALLI MongoDB] User admin role lookup error: {ex}") # 4. In-memory fallback mem_doc = self._admin_emails_store.get(normalized) if mem_doc and mem_doc.get("status") != "disabled": return True return False def list_admin_emails(self) -> List[Dict[str, Any]]: """List all registered administrative emails from database.""" col = self.get_collection("admin_emails") if col is not None: try: docs = list(col.find({}, {"_id": 0})) existing_emails = {d["email"] for d in docs if "email" in d} for email, record in self._admin_emails_store.items(): if email not in existing_emails and record.get("status") != "disabled": docs.append(record) return docs except Exception as ex: print(f"[ALLI MongoDB] Admin email list error: {ex}") return list(self._admin_emails_store.values()) def add_admin_email( self, email: str, role: str = "admin", added_by: Optional[str] = None, ) -> Dict[str, Any]: """Register or activate an administrative email in MongoDB.""" normalized = email.strip().lower() now = get_utc_now() doc = { "email": normalized, "role": role, "status": "active", "added_at": now, "added_by": added_by or "admin", "updated_at": now, } col = self.get_collection("admin_emails") if col is not None: try: col.update_one({"email": normalized}, {"$set": doc}, upsert=True) saved = col.find_one({"email": normalized}, {"_id": 0}) if saved: return saved except Exception as ex: print(f"[ALLI MongoDB] Admin email insert error: {ex}") self._admin_emails_store[normalized] = doc return doc def remove_admin_email(self, email: str) -> bool: """Revoke admin privileges by removing or disabling the email in MongoDB.""" normalized = email.strip().lower() col = self.get_collection("admin_emails") if col is not None: try: res = col.delete_one({"email": normalized}) if res.deleted_count > 0: self._admin_emails_store.pop(normalized, None) return True except Exception as ex: print(f"[ALLI MongoDB] Admin email deletion error: {ex}") if normalized in self._admin_emails_store: del self._admin_emails_store[normalized] return True return False