Create database.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import jsonimport httpxfrom config import SUPABASE_URL, SUPABASE_KEY, user_tokens
async def save_token_to_supabase(user_id: str, service: str, token_data: dict): google_services = ["google", "gmail", "calendar", "drive"] target_services = google_services if service in google_services else [service] for s in target_services: user_tokens[(user_id, s)] = token_data try: url = f"{SUPABASE_URL}/rest/v1/user_connectors" headers = { "apikey": SUPABASE_KEY, "Authorization": f"Bearer {SUPABASE_KEY}", "Content-Type": "application/json", "Prefer": "resolution=merge-duplicates" } payload = { "user_id": user_id, "service": s, "token_data": token_data } async with httpx.AsyncClient() as c: await c.post(url, headers=headers, json=payload) except Exception: pass
async def get_token_from_supabase(user_id: str, service: str): check_services = [service, "google", "gmail", "calendar", "drive"] if service in ["google", "gmail", "calendar", "drive"] else [service] for s in check_services: if (user_id, s) in user_tokens: return user_tokens[(user_id, s)] try: url = f"{SUPABASE_URL}/rest/v1/user_connectors?user_id=eq.{user_id}&service=eq.{s}" headers = { "apikey": SUPABASE_KEY, "Authorization": f"Bearer {SUPABASE_KEY}" } async with httpx.AsyncClient() as c: res = await c.get(url, headers=headers) if res.status_code == 200: data = res.json() if data and len(data) > 0: raw_t = data[0].get("token_data") if isinstance(raw_t, dict): t_data = raw_t elif isinstance(raw_t, str): t_data = json.loads(raw_t) else: t_data = {} if t_data: user_tokens[(user_id, s)] = t_data return t_data except Exception: pass return Nonedatabase.pyAdded+57