70 lines
2.6 KiB
Python
70 lines
2.6 KiB
Python
|
|
import os
|
|
import urllib.parse
|
|
import requests
|
|
from nicegui import ui, app
|
|
import database
|
|
|
|
def get_auth_url():
|
|
client_id = os.getenv("DISCORD_CLIENT_ID")
|
|
app_url = os.getenv("APP_URL")
|
|
redirect_uri = f"{app_url}/login/discord"
|
|
encoded_redirect_uri = urllib.parse.quote(redirect_uri, safe="")
|
|
|
|
# NEU: scope=identify%20guilds fragt Profilbild UND Server ab
|
|
return f"https://discord.com/api/oauth2/authorize?client_id={client_id}&redirect_uri={encoded_redirect_uri}&response_type=code&scope=identify%20guilds"
|
|
|
|
def setup_login_routes():
|
|
client_id = os.getenv("DISCORD_CLIENT_ID")
|
|
client_secret = os.getenv("DISCORD_CLIENT_SECRET")
|
|
app_url = os.getenv("APP_URL")
|
|
redirect_uri = f"{app_url}/login/discord"
|
|
|
|
@ui.page('/login/discord')
|
|
def discord_callback(code: str = None):
|
|
if not code:
|
|
ui.label('Fehler: Kein Code erhalten.').classes('text-red-500')
|
|
return
|
|
|
|
token_data = {
|
|
'client_id': client_id,
|
|
'client_secret': client_secret,
|
|
'grant_type': 'authorization_code',
|
|
'code': code,
|
|
'redirect_uri': redirect_uri
|
|
}
|
|
|
|
token_response = requests.post('https://discord.com/api/oauth2/token', data=token_data)
|
|
token_json = token_response.json()
|
|
|
|
if 'access_token' in token_json:
|
|
access_token = token_json['access_token']
|
|
|
|
user_headers = {'Authorization': f"Bearer {access_token}"}
|
|
user_response = requests.get('https://discord.com/api/users/@me', headers=user_headers)
|
|
user_json = user_response.json()
|
|
|
|
discord_id = user_json['id']
|
|
discord_name = user_json['username']
|
|
|
|
# --- BILD ABFANGEN ---
|
|
avatar_hash = user_json.get('avatar')
|
|
if avatar_hash:
|
|
avatar_url = f"https://cdn.discordapp.com/avatars/{discord_id}/{avatar_hash}.png"
|
|
else:
|
|
avatar_url = "https://cdn.discordapp.com/embed/avatars/0.png"
|
|
|
|
# In die Datenbank eintragen
|
|
player = database.get_or_create_player(discord_id, discord_name, avatar_url)
|
|
|
|
# Session updaten
|
|
app.storage.user['authenticated'] = True
|
|
app.storage.user['discord_id'] = discord_id
|
|
app.storage.user['discord_name'] = discord_name
|
|
app.storage.user['db_id'] = player[0]
|
|
app.storage.user['display_name'] = player[2]
|
|
app.storage.user['discord_avatar_url'] = player[3] # Bild speichern!
|
|
|
|
ui.navigate.to('/')
|
|
else:
|
|
ui.label('Fehler beim Login!').classes('text-red-500') |