Initial commit: FlexiCraft Web Portal + Discord SSO + Quartz/Iron engines
This commit is contained in:
commit
f488ff57c5
19 changed files with 3256 additions and 0 deletions
64
core/discord_oauth.py
Normal file
64
core/discord_oauth.py
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import os, urllib.parse, httpx
|
||||
|
||||
GUILD_ID = "645626003594412061"
|
||||
DISCORD_API = "https://discord.com" + "/api/v10"
|
||||
DISCORD_AUTH = "https://discord.com" + "/oauth2/authorize"
|
||||
REDIRECT_URI = "https://flexicraft.eu" + "/auth/discord/callback"
|
||||
|
||||
def get_authorize_url(state: str) -> str:
|
||||
client_id = os.environ.get("DISCORD_CLIENT_ID", "")
|
||||
params = {
|
||||
"client_id": client_id,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"response_type": "code",
|
||||
"scope": "identify guilds.members.read",
|
||||
"state": state
|
||||
}
|
||||
return DISCORD_AUTH + "?" + urllib.parse.urlencode(params)
|
||||
|
||||
async def exchange_code_and_fetch_member(code: str) -> dict:
|
||||
client_id = os.environ.get("DISCORD_CLIENT_ID", "")
|
||||
client_secret = os.environ.get("DISCORD_CLIENT_SECRET", "")
|
||||
bot_token = os.environ.get("DISCORD_BOT_TOKEN", "")
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
token_resp = await client.post(
|
||||
DISCORD_API + "/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_resp.raise_for_status()
|
||||
access_token = token_resp.json()["access_token"]
|
||||
|
||||
user_resp = await client.get(
|
||||
DISCORD_API + "/users/@me",
|
||||
headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
user_resp.raise_for_status()
|
||||
u = user_resp.json()
|
||||
|
||||
roles = []
|
||||
nick = u.get("global_name") or u.get("username")
|
||||
if bot_token:
|
||||
mem_resp = await client.get(
|
||||
f"{DISCORD_API}/guilds/{GUILD_ID}/members/{u['id']}",
|
||||
headers={"Authorization": f"Bot {bot_token}"}
|
||||
)
|
||||
if mem_resp.status_code == 200:
|
||||
mdata = mem_resp.json()
|
||||
roles = mdata.get("roles", [])
|
||||
if mdata.get("nick"):
|
||||
nick = mdata["nick"]
|
||||
|
||||
return {
|
||||
"id": u["id"],
|
||||
"username": nick,
|
||||
"avatar": u.get("avatar"),
|
||||
"roles": roles
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue