T7yrttrd commited on
Commit
bdb6caf
·
verified ·
1 Parent(s): 3c60840

Create database.py

Browse files
Files changed (1) hide show
  1. database.py +57 -0
database.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import httpx
3
+ from config import SUPABASE_URL, SUPABASE_KEY, user_tokens
4
+
5
+ async def save_token_to_supabase(user_id: str, service: str, token_data: dict):
6
+ google_services = ["google", "gmail", "calendar", "drive"]
7
+ target_services = google_services if service in google_services else [service]
8
+
9
+ for s in target_services:
10
+ user_tokens[(user_id, s)] = token_data
11
+ try:
12
+ url = f"{SUPABASE_URL}/rest/v1/user_connectors"
13
+ headers = {
14
+ "apikey": SUPABASE_KEY,
15
+ "Authorization": f"Bearer {SUPABASE_KEY}",
16
+ "Content-Type": "application/json",
17
+ "Prefer": "resolution=merge-duplicates"
18
+ }
19
+ payload = {
20
+ "user_id": user_id,
21
+ "service": s,
22
+ "token_data": token_data
23
+ }
24
+ async with httpx.AsyncClient() as c:
25
+ await c.post(url, headers=headers, json=payload)
26
+ except Exception:
27
+ pass
28
+
29
+ async def get_token_from_supabase(user_id: str, service: str):
30
+ check_services = [service, "google", "gmail", "calendar", "drive"] if service in ["google", "gmail", "calendar", "drive"] else [service]
31
+ for s in check_services:
32
+ if (user_id, s) in user_tokens:
33
+ return user_tokens[(user_id, s)]
34
+ try:
35
+ url = f"{SUPABASE_URL}/rest/v1/user_connectors?user_id=eq.{user_id}&service=eq.{s}"
36
+ headers = {
37
+ "apikey": SUPABASE_KEY,
38
+ "Authorization": f"Bearer {SUPABASE_KEY}"
39
+ }
40
+ async with httpx.AsyncClient() as c:
41
+ res = await c.get(url, headers=headers)
42
+ if res.status_code == 200:
43
+ data = res.json()
44
+ if data and len(data) > 0:
45
+ raw_t = data[0].get("token_data")
46
+ if isinstance(raw_t, dict):
47
+ t_data = raw_t
48
+ elif isinstance(raw_t, str):
49
+ t_data = json.loads(raw_t)
50
+ else:
51
+ t_data = {}
52
+ if t_data:
53
+ user_tokens[(user_id, s)] = t_data
54
+ return t_data
55
+ except Exception:
56
+ pass
57
+ return None