Advertisement
NaroxEG

Discord Auth. | Flask

Jul 31st, 2024 (edited)
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. from flask import Flask, redirect, url_for, render_template, request, session
  2. import requests
  3. import os
  4. from urllib.parse import urlencode
  5.  
  6. app = Flask(__name__)
  7. app.secret_key = os.urandom(24)
  8.  
  9. CLIENT_ID = "CLIENT_ID"
  10. CLIENT_SECRET = "CLIENT_SECRET"
  11. REDIRECT_URI = "http://localhost:5000/callback"
  12. DISCORD_API_ENDPOINT = "https://discord.com/api/v10/"
  13.  
  14. @app.route('/')
  15. def home():
  16.     return render_template('home.html')
  17.  
  18. @app.route('/login')
  19. def login():
  20.     params = {
  21.         "client_id": CLIENT_ID,
  22.         "redirect_uri": REDIRECT_URI,
  23.         "response_type": "code",
  24.         "scope": "identify email"
  25.     }
  26.     return redirect(f"https://discord.com/api/oauth2/authorize?{urlencode(params)}")
  27.  
  28. @app.route('/callback')
  29. def callback():
  30.     code = request.args.get("code")
  31.     if not code:
  32.         return "No code provided", 400
  33.    
  34.     data = {
  35.         "client_id": CLIENT_ID,
  36.         "client_secret": CLIENT_SECRET,
  37.         "grant_type": "authorization_code",
  38.         "code": code,
  39.         "redirect_uri": REDIRECT_URI
  40.     }
  41.     response = requests.post(f"{DISCORD_API_ENDPOINT}/oauth2/token", data=data)
  42.     if response.status_code != 200:
  43.         return "Failed to get access token", 400
  44.    
  45.     token_data = response.json()
  46.     session["access_token"] = token_data["access_token"]
  47.  
  48.     return redirect(url_for('dashboard'))
  49.  
  50. @app.route('/dashboard')
  51. def dashboard():
  52.     if "access_token" not in session:
  53.         return redirect(url_for('login'))
  54.    
  55.     session_token = session["access_token"]
  56.     headers = {
  57.         "Authorization": f"Bearer {session_token}"
  58.     }
  59.     response = requests.get(f"{DISCORD_API_ENDPOINT}/users/@me", headers=headers)
  60.     if response.status_code != 200:
  61.         return "Failed to get user information", 400
  62.    
  63.     user_data = response.json()
  64.  
  65.     return render_template("dash.html", user=user_data)
  66.  
  67. if __name__ == "__main__":
  68.     app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement