Create collaboration.py
Browse files- routes/collaboration.py +124 -0
routes/collaboration.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import logging
|
3 |
+
import aiohttp
|
4 |
+
from fastapi import APIRouter, HTTPException, Header
|
5 |
+
from pydantic import BaseModel
|
6 |
+
from typing import Optional
|
7 |
+
|
8 |
+
router = APIRouter()
|
9 |
+
|
10 |
+
# 🔧 Supabase Config
|
11 |
+
SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
|
12 |
+
SUPABASE_KEY = os.getenv("SUPA_KEY")
|
13 |
+
SUPABASE_ROLE_KEY = os.getenv("SUPA_SERVICE_KEY")
|
14 |
+
|
15 |
+
if not SUPABASE_KEY or not SUPABASE_ROLE_KEY:
|
16 |
+
raise ValueError("❌ SUPA_KEY or SUPA_SERVICE_KEY not set in environment!")
|
17 |
+
|
18 |
+
SUPABASE_HEADERS = {
|
19 |
+
"apikey": SUPABASE_KEY,
|
20 |
+
"Authorization": f"Bearer {SUPABASE_KEY}",
|
21 |
+
"Content-Type": "application/json"
|
22 |
+
}
|
23 |
+
|
24 |
+
SUPABASE_ROLE_HEADERS = {
|
25 |
+
"apikey": SUPABASE_ROLE_KEY,
|
26 |
+
"Authorization": f"Bearer {SUPABASE_ROLE_KEY}",
|
27 |
+
"Content-Type": "application/json"
|
28 |
+
}
|
29 |
+
|
30 |
+
# 🔍 Model
|
31 |
+
class CreateCollaborationRequest(BaseModel):
|
32 |
+
email: str
|
33 |
+
password: str
|
34 |
+
|
35 |
+
# ✅ Verifica se o token pertence a um admin
|
36 |
+
async def verify_admin_token(user_token: str) -> str:
|
37 |
+
headers = {
|
38 |
+
"Authorization": f"Bearer {user_token}",
|
39 |
+
"apikey": SUPABASE_KEY,
|
40 |
+
"Content-Type": "application/json"
|
41 |
+
}
|
42 |
+
|
43 |
+
async with aiohttp.ClientSession() as session:
|
44 |
+
async with session.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers) as response:
|
45 |
+
if response.status != 200:
|
46 |
+
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
47 |
+
|
48 |
+
user_data = await response.json()
|
49 |
+
user_id = user_data.get("id")
|
50 |
+
if not user_id:
|
51 |
+
raise HTTPException(status_code=400, detail="User ID not found")
|
52 |
+
|
53 |
+
# Verifica se é admin na tabela User
|
54 |
+
async with aiohttp.ClientSession() as session:
|
55 |
+
async with session.get(
|
56 |
+
f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}",
|
57 |
+
headers=SUPABASE_HEADERS
|
58 |
+
) as resp:
|
59 |
+
if resp.status != 200:
|
60 |
+
raise HTTPException(status_code=403, detail="Could not verify admin status")
|
61 |
+
|
62 |
+
user_info = await resp.json()
|
63 |
+
if not user_info or not user_info[0].get("is_admin", False):
|
64 |
+
raise HTTPException(status_code=403, detail="Admin privileges required")
|
65 |
+
|
66 |
+
return user_id
|
67 |
+
|
68 |
+
# ➕ Criar colaborador
|
69 |
+
@router.post("/admin/create-collaboration")
|
70 |
+
async def create_collaboration(
|
71 |
+
body: CreateCollaborationRequest,
|
72 |
+
user_token: str = Header(None, alias="User-key")
|
73 |
+
):
|
74 |
+
try:
|
75 |
+
await verify_admin_token(user_token)
|
76 |
+
|
77 |
+
# 1. Cria o novo usuário com Admin API
|
78 |
+
create_user_payload = {
|
79 |
+
"email": body.email,
|
80 |
+
"password": body.password,
|
81 |
+
"email_confirm": True
|
82 |
+
}
|
83 |
+
|
84 |
+
async with aiohttp.ClientSession() as session:
|
85 |
+
async with session.post(
|
86 |
+
f"{SUPABASE_URL}/auth/v1/admin/users",
|
87 |
+
headers=SUPABASE_ROLE_HEADERS,
|
88 |
+
json=create_user_payload
|
89 |
+
) as user_response:
|
90 |
+
|
91 |
+
if user_response.status != 200:
|
92 |
+
error_detail = await user_response.json()
|
93 |
+
raise HTTPException(status_code=400, detail=error_detail.get("msg", "Failed to create user"))
|
94 |
+
|
95 |
+
user_data = await user_response.json()
|
96 |
+
user_id = user_data.get("id")
|
97 |
+
if not user_id:
|
98 |
+
raise HTTPException(status_code=500, detail="User ID not returned after creation")
|
99 |
+
|
100 |
+
# 2. Cria o registro na tabela "User" com is_admin = true
|
101 |
+
user_insert_payload = {
|
102 |
+
"id": user_id,
|
103 |
+
"email": body.email,
|
104 |
+
"is_admin": True
|
105 |
+
}
|
106 |
+
|
107 |
+
async with aiohttp.ClientSession() as session:
|
108 |
+
async with session.post(
|
109 |
+
f"{SUPABASE_URL}/rest/v1/User",
|
110 |
+
headers=SUPABASE_ROLE_HEADERS,
|
111 |
+
json=user_insert_payload
|
112 |
+
) as insert_response:
|
113 |
+
|
114 |
+
if insert_response.status != 201:
|
115 |
+
error_detail = await insert_response.text()
|
116 |
+
raise HTTPException(status_code=500, detail="Failed to insert user into User table")
|
117 |
+
|
118 |
+
return {"success": True}
|
119 |
+
|
120 |
+
except HTTPException as http_ex:
|
121 |
+
return {"success": False, "detail": http_ex.detail}
|
122 |
+
except Exception as e:
|
123 |
+
logging.error(f"❌ Unexpected error: {str(e)}")
|
124 |
+
return {"success": False, "detail": str(e)}
|