DBFahrerKaterchen3 commited on
Commit
36c51cc
·
verified ·
1 Parent(s): bbb6b8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -54
app.py CHANGED
@@ -1,17 +1,22 @@
1
  import os
2
  import urllib.parse
3
  from fastapi import FastAPI, HTTPException
4
- from fastapi.responses import HTMLResponse
5
- import httpx
6
 
7
  app = FastAPI()
8
 
9
  CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
10
  CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")
11
- REDIRECT_URI = "https://rsbtech-rsbtech-verification.hf.space/oauth/callback"
 
 
 
 
12
 
13
  @app.get("/", response_class=HTMLResponse)
14
  async def home():
 
15
  scopes = "identify role_connections.write"
16
  encoded_redirect = urllib.parse.quote(REDIRECT_URI, safe='')
17
 
@@ -40,6 +45,7 @@ async def oauth_callback(code: str = None):
40
  if not code:
41
  raise HTTPException(status_code=400, detail="Kein Code vorhanden.")
42
 
 
43
  token_url = "https://discord.com/api/v10/oauth2/token"
44
  data = {
45
  "client_id": CLIENT_ID,
@@ -50,58 +56,44 @@ async def oauth_callback(code: str = None):
50
  }
51
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
52
 
53
- # Wir erstellen ein Transport-Objekt, das explizit IPv4 erzwingt (verhindert hängende Routen)
54
- transport = httpx.AsyncHTTPTransport(local_address="0.0.0.0")
55
 
56
- async with httpx.AsyncClient(verify=False, transport=transport) as client:
57
- try:
58
- # 1. Code gegen Token tauschen
59
- token_res = await client.post(token_url, data=data, headers=headers, timeout=15.0)
60
- token_data = token_res.json()
61
-
62
- if "access_token" not in token_data:
63
- return HTMLResponse(f"<h3 style='color:red;'>Discord Fehler beim Token-Austausch: {token_data}</h3>")
64
-
65
- access_token = token_data["access_token"]
66
 
67
- # 2. Nutzerdaten holen
68
- user_res = await client.get("https://discord.com/api/v10/users/@me", headers={
69
- "Authorization": f"Bearer {access_token}"
70
- }, timeout=15.0)
71
- user_json = user_res.json()
72
- username = user_json.get("username", "Nutzer")
73
 
74
- # 3. Linked Roles Metadaten an Discord übermitteln
75
- connection_url = f"https://discord.com/api/v10/users/@me/applications/{CLIENT_ID}/role-connection"
76
- connection_body = {
77
- "platform_name": "HF Space Anmeldung",
78
- "platform_username": username,
79
- "metadata": {
80
- "is_verified": 1
81
- }
82
- }
83
-
84
- put_res = await client.put(connection_url, json=connection_body, headers={
85
- "Authorization": f"Bearer {access_token}",
86
- "Content-Type": "application/json"
87
- }, timeout=15.0)
 
 
88
 
89
- if put_res.status_code == 200:
90
- return HTMLResponse(f"""
91
- <body style="font-family: Arial; text-align: center; padding-top: 100px; background-color: #23272A; color: white;">
92
- <h2 style="color: #57F287;">Erfolgreich verbunden, {username}!</h2>
93
- <p>Du kannst dieses Fenster jetzt schließen und deine Rolle auf Discord abholen.</p>
94
- </body>
95
- """)
96
- else:
97
- return HTMLResponse(f"<h3 style='color:red;'>Metadaten-Fehler: {put_res.text}</h3>")
98
-
99
- except Exception as e:
100
- # Zeigt uns jetzt den exakten Systemfehler (z.B. Timeout oder ConnectionRefused)
101
- return HTMLResponse(f"""
102
- <body style="font-family: Arial; background-color: #23272A; color: white; padding: 20px;">
103
- <h3 style="color: #ED4245;">Netzwerk-Fehler im Space-Backend:</h3>
104
- <p><b>Details:</b> {type(e).__name__} - {str(e)}</p>
105
- <p>Falls hier 'TimeoutException' steht, blockiert Hugging Face ausgehende API-Anrufe.</p>
106
- </body>
107
- """)
 
1
  import os
2
  import urllib.parse
3
  from fastapi import FastAPI, HTTPException
4
+ from fastapi.responses import HTMLResponse, RedirectResponse
5
+ import requests
6
 
7
  app = FastAPI()
8
 
9
  CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
10
  CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")
11
+
12
+ # WICHTIG: Passe diese URL an deinen HF-Namen und Space-Namen an!
13
+ # Format: https://username-space-name.hf.space/oauth/callback
14
+ # Achtung: Bindestriche statt Slashes im Domain-Namen!
15
+ REDIRECT_URI = "https://DEIN_USERNAME-DEIN_SPACE_NAME.hf.space/oauth/callback"
16
 
17
  @app.get("/", response_class=HTMLResponse)
18
  async def home():
19
+ # Der Link, der den Nutzer zu Discord schickt, um die App zu autorisieren
20
  scopes = "identify role_connections.write"
21
  encoded_redirect = urllib.parse.quote(REDIRECT_URI, safe='')
22
 
 
45
  if not code:
46
  raise HTTPException(status_code=400, detail="Kein Code vorhanden.")
47
 
48
+ # 1. Code gegen Token tauschen
49
  token_url = "https://discord.com/api/v10/oauth2/token"
50
  data = {
51
  "client_id": CLIENT_ID,
 
56
  }
57
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
58
 
59
+ token_res = requests.post(token_url, data=data, headers=headers)
60
+ token_data = token_res.json()
61
 
62
+ if "access_token" not in token_data:
63
+ return HTMLResponse(f"<h3 style='color:red;'>Fehler beim Login: {token_data}</h3>")
64
+
65
+ access_token = token_data["access_token"]
 
 
 
 
 
 
66
 
67
+ # 2. Nutzerdaten holen (um den Namen anzuzeigen)
68
+ user_res = requests.get("https://discord.com/api/v10/users/@me", headers={
69
+ "Authorization": f"Bearer {access_token}"
70
+ })
71
+ user_json = user_res.json()
72
+ username = user_json.get("username", "Nutzer")
73
 
74
+ # 3. Linked Roles Metadaten an Discord übermitteln
75
+ # Hier sagen wir Discord, dass 'is_verified' für diesen Nutzer nun True (1) ist
76
+ connection_url = f"https://discord.com/api/v10/users/@me/applications/{CLIENT_ID}/role-connection"
77
+
78
+ connection_body = {
79
+ "platform_name": "HF Space Anmeldung",
80
+ "platform_username": username,
81
+ "metadata": {
82
+ "is_verified": 1 # 1 steht für True
83
+ }
84
+ }
85
+
86
+ put_res = requests.put(connection_url, json=connection_body, headers={
87
+ "Authorization": f"Bearer {access_token}",
88
+ "Content-Type": "application/json"
89
+ })
90
 
91
+ if put_res.status_code == 200:
92
+ return HTMLResponse(f"""
93
+ <body style="font-family: Arial; text-align: center; padding-top: 100px; background-color: #23272A; color: white;">
94
+ <h2 style="color: #57F287;">Erfolgreich verbunden, {username}!</h2>
95
+ <p>Du kannst dieses Fenster jetzt schließen und deine Rolle auf Discord abholen.</p>
96
+ </body>
97
+ """)
98
+ else:
99
+ return HTMLResponse(f"<h3 style='color:red;'>Metadaten-Fehler: {put_res.text}</h3>")