import json from datetime import datetime, timezone class AccessControl: _ACCESS_FILE = "./data/access.json" def __init__(self): self._access = self._load_access() def _load_access(self) -> dict: try: with open(self._ACCESS_FILE, "r") as f: return json.load(f) except FileNotFoundError: return {} def _save_access(self): with open(self._ACCESS_FILE, "w") as f: json.dump(self._access, f) def get_grantor(self, user_id: str, gate: str) -> str: access = self._access.get(user_id, {}) entry = access.get(gate) or access.get("all") return entry.get("grantor", "") if entry else "" def can_open_gate(self, user_id: str, gate: str) -> bool: access = self._access.get(user_id, {}) entry = access.get(gate) or access.get("all") if not entry or entry.get("type") != "timed": return False if datetime.now(timezone.utc) < datetime.fromisoformat(entry["expires_at"].replace("Z", "+00:00")): return True return False def grant_access(self, user_id: str, gate: str, expires_at: str, grantor_id: str): user_access = self._access.get(user_id, {}) user_access[gate] = { "type": "timed", "granted_at": datetime.now(timezone.utc).isoformat(), "expires_at": expires_at, "grantor": grantor_id, "last_used_at": None } self._access[user_id] = user_access self._save_access()