File size: 3,825 Bytes
10fd371
 
 
36c51cc
 
10fd371
 
 
 
 
36c51cc
 
 
 
f73972a
10fd371
 
 
36c51cc
10fd371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36c51cc
10fd371
 
 
 
 
 
 
 
 
 
36c51cc
 
bbb6b8c
36c51cc
 
 
 
10fd371
36c51cc
 
 
 
 
 
10fd371
36c51cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10fd371
36c51cc
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import os
import urllib.parse
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
import requests

app = FastAPI()

CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")

# WICHTIG: Passe diese URL an deinen HF-Namen und Space-Namen an!
# Format: https://username-space-name.hf.space/oauth/callback
# Achtung: Bindestriche statt Slashes im Domain-Namen!
REDIRECT_URI = "https://RSBtech-rsbtech-verification.hf.space/oauth/callback"

@app.get("/", response_class=HTMLResponse)
async def home():
    # Der Link, der den Nutzer zu Discord schickt, um die App zu autorisieren
    scopes = "identify role_connections.write"
    encoded_redirect = urllib.parse.quote(REDIRECT_URI, safe='')
    
    discord_url = (
        f"https://discord.com/api/oauth2/authorize"
        f"?client_id={CLIENT_ID}"
        f"&redirect_uri={encoded_redirect}"
        f"&response_type=code"
        f"&scope={scopes}"
    )
    
    return f"""
    <html>
        <head><title>Discord Verifizierung</title></head>
        <body style="font-family: Arial; text-align: center; padding-top: 100px; background-color: #23272A; color: white;">
            <h2>Discord Rollen-Verknüpfung</h2>
            <p>Klicke auf den Button, um dich anzumelden und deine Rolle freizuschalten.</p>
            <br>
            <a href="{discord_url}" style="background-color: #5865F2; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; font-weight: bold;">Mit Discord verbinden</a>
        </body>
    </html>
    """

@app.get("/oauth/callback")
async def oauth_callback(code: str = None):
    if not code:
        raise HTTPException(status_code=400, detail="Kein Code vorhanden.")

    # 1. Code gegen Token tauschen
    token_url = "https://discord.com/api/v10/oauth2/token"
    data = {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI
    }
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    
    token_res = requests.post(token_url, data=data, headers=headers)
    token_data = token_res.json()
    
    if "access_token" not in token_data:
        return HTMLResponse(f"<h3 style='color:red;'>Fehler beim Login: {token_data}</h3>")
        
    access_token = token_data["access_token"]

    # 2. Nutzerdaten holen (um den Namen anzuzeigen)
    user_res = requests.get("https://discord.com/api/v10/users/@me", headers={
        "Authorization": f"Bearer {access_token}"
    })
    user_json = user_res.json()
    username = user_json.get("username", "Nutzer")

    # 3. Linked Roles Metadaten an Discord übermitteln
    # Hier sagen wir Discord, dass 'is_verified' für diesen Nutzer nun True (1) ist
    connection_url = f"https://discord.com/api/v10/users/@me/applications/{CLIENT_ID}/role-connection"
    
    connection_body = {
        "platform_name": "HF Space Anmeldung",
        "platform_username": username,
        "metadata": {
            "is_verified": 1  # 1 steht für True
        }
    }
    
    put_res = requests.put(connection_url, json=connection_body, headers={
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    })

    if put_res.status_code == 200:
        return HTMLResponse(f"""
        <body style="font-family: Arial; text-align: center; padding-top: 100px; background-color: #23272A; color: white;">
            <h2 style="color: #57F287;">Erfolgreich verbunden, {username}!</h2>
            <p>Du kannst dieses Fenster jetzt schließen und deine Rolle auf Discord abholen.</p>
        </body>
        """)
    else:
        return HTMLResponse(f"<h3 style='color:red;'>Metadaten-Fehler: {put_res.text}</h3>")