T7yrttrd's picture
Update database.py
aac483f verified
Raw History Blame
3.72 kB
import json
import httpx
from 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"]
ms_services = ["microsoft", "teams", "word", "excel", "powerpoint"]
if service in google_services:
target_services = google_services
elif service in ms_services:
target_services = ms_services
else:
target_services = [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(timeout=15.0) as c:
await c.post(url, headers=headers, json=payload)
except Exception:
pass
async def get_token_from_supabase(user_id: str, service: str):
google_services = ["google", "gmail", "calendar", "drive"]
ms_services = ["microsoft", "teams", "word", "excel", "powerpoint"]
if service in google_services:
check_services = [service] + [x for x in google_services if x != service]
elif service in ms_services:
check_services = [service] + [x for x in ms_services if x != service]
else:
check_services = [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}&select=token_data"
headers = {
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}"
}
async with httpx.AsyncClient(timeout=15.0) 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 None
async def delete_token_from_supabase(user_id: str, service: str):
google_services = ["google", "gmail", "calendar", "drive"]
ms_services = ["microsoft", "teams", "word", "excel", "powerpoint"]
if service in google_services:
target_services = google_services
elif service in ms_services:
target_services = ms_services
else:
target_services = [service]
for s in target_services:
user_tokens.pop((user_id, s), None)
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(timeout=15.0) as c:
await c.delete(url, headers=headers)
except Exception:
pass