|
| 1 | +"""Discord OAuth2 forward-auth proxy for the Modmail logviewer. |
| 2 | +
|
| 3 | +Sits behind Caddy's `forward_auth`. Visitors are sent through Discord's OAuth2 |
| 4 | +flow; only members of GUILD_ID who hold REQUIRED_ROLE_ID are issued a signed |
| 5 | +session cookie and allowed through to the logviewer. |
| 6 | +
|
| 7 | +Endpoints (all under /auth, routed straight to this service by Caddy): |
| 8 | + /auth/verify - called by Caddy for every request; 200 if authed, else 302 to login |
| 9 | + /auth/login - starts the Discord OAuth2 flow |
| 10 | + /auth/callback - Discord redirects here; verifies role, sets session cookie |
| 11 | + /auth/logout - clears the session cookie |
| 12 | +""" |
| 13 | + |
| 14 | +import os |
| 15 | +import time |
| 16 | +import secrets |
| 17 | +import urllib.parse |
| 18 | + |
| 19 | +import requests |
| 20 | +from flask import Flask, request, redirect, make_response |
| 21 | +from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired |
| 22 | + |
| 23 | +CLIENT_ID = os.environ["DISCORD_CLIENT_ID"] |
| 24 | +CLIENT_SECRET = os.environ["DISCORD_CLIENT_SECRET"] |
| 25 | +REDIRECT_URI = os.environ["DISCORD_REDIRECT_URI"] # https://<domain>/auth/callback |
| 26 | +GUILD_ID = os.environ["GUILD_ID"] |
| 27 | +REQUIRED_ROLE_ID = os.environ["REQUIRED_ROLE_ID"] |
| 28 | +SECRET_KEY = os.environ["SESSION_SECRET"] |
| 29 | + |
| 30 | +COOKIE_NAME = os.environ.get("SESSION_COOKIE_NAME", "modmail_logs_session") |
| 31 | +SESSION_TTL = int(os.environ.get("SESSION_TTL", "86400")) # 24h |
| 32 | + |
| 33 | +API_BASE = "https://discord.com/api" |
| 34 | +SCOPES = "identify guilds.members.read" |
| 35 | + |
| 36 | +app = Flask(__name__) |
| 37 | +session_signer = URLSafeTimedSerializer(SECRET_KEY, salt="modmail-logs-session") |
| 38 | +state_signer = URLSafeTimedSerializer(SECRET_KEY, salt="modmail-logs-state") |
| 39 | + |
| 40 | + |
| 41 | +def _redirect_to_login(): |
| 42 | + """Send the browser into Discord's OAuth2 flow, remembering where it wanted to go.""" |
| 43 | + original = request.headers.get("X-Forwarded-Uri", "/") |
| 44 | + state = state_signer.dumps({"nonce": secrets.token_urlsafe(8), "dest": original}) |
| 45 | + params = urllib.parse.urlencode( |
| 46 | + { |
| 47 | + "client_id": CLIENT_ID, |
| 48 | + "response_type": "code", |
| 49 | + "redirect_uri": REDIRECT_URI, |
| 50 | + "scope": SCOPES, |
| 51 | + "state": state, |
| 52 | + } |
| 53 | + ) |
| 54 | + return redirect(f"{API_BASE}/oauth2/authorize?{params}") |
| 55 | + |
| 56 | + |
| 57 | +@app.route("/auth/verify") |
| 58 | +def verify(): |
| 59 | + token = request.cookies.get(COOKIE_NAME) |
| 60 | + if token: |
| 61 | + try: |
| 62 | + session_signer.loads(token, max_age=SESSION_TTL) |
| 63 | + return ("", 200) |
| 64 | + except (BadSignature, SignatureExpired): |
| 65 | + pass |
| 66 | + return _redirect_to_login() |
| 67 | + |
| 68 | + |
| 69 | +@app.route("/auth/login") |
| 70 | +def login(): |
| 71 | + return _redirect_to_login() |
| 72 | + |
| 73 | + |
| 74 | +@app.route("/auth/callback") |
| 75 | +def callback(): |
| 76 | + code = request.args.get("code") |
| 77 | + state = request.args.get("state") |
| 78 | + if not code or not state: |
| 79 | + return ("Missing code or state.", 400) |
| 80 | + try: |
| 81 | + state_data = state_signer.loads(state, max_age=600) |
| 82 | + except (BadSignature, SignatureExpired): |
| 83 | + return ("Invalid or expired login attempt. Please try again.", 400) |
| 84 | + |
| 85 | + # Exchange the authorization code for an access token. |
| 86 | + token_resp = requests.post( |
| 87 | + f"{API_BASE}/oauth2/token", |
| 88 | + data={ |
| 89 | + "client_id": CLIENT_ID, |
| 90 | + "client_secret": CLIENT_SECRET, |
| 91 | + "grant_type": "authorization_code", |
| 92 | + "code": code, |
| 93 | + "redirect_uri": REDIRECT_URI, |
| 94 | + }, |
| 95 | + headers={"Content-Type": "application/x-www-form-urlencoded"}, |
| 96 | + timeout=10, |
| 97 | + ) |
| 98 | + if token_resp.status_code != 200: |
| 99 | + return ("Discord token exchange failed.", 403) |
| 100 | + access_token = token_resp.json().get("access_token") |
| 101 | + |
| 102 | + # Read the caller's member object for the guild (includes their role IDs). |
| 103 | + member_resp = requests.get( |
| 104 | + f"{API_BASE}/users/@me/guilds/{GUILD_ID}/member", |
| 105 | + headers={"Authorization": f"Bearer {access_token}"}, |
| 106 | + timeout=10, |
| 107 | + ) |
| 108 | + if member_resp.status_code != 200: |
| 109 | + return ("You are not a member of the required server.", 403) |
| 110 | + member = member_resp.json() |
| 111 | + if REQUIRED_ROLE_ID not in member.get("roles", []): |
| 112 | + return ("You do not have the required role to view these logs.", 403) |
| 113 | + |
| 114 | + # Authorised: issue a signed session cookie and return to the original page. |
| 115 | + user_id = member.get("user", {}).get("id") |
| 116 | + value = session_signer.dumps({"id": user_id, "ts": int(time.time())}) |
| 117 | + dest = state_data.get("dest", "/") |
| 118 | + if not dest.startswith("/"): |
| 119 | + dest = "/" |
| 120 | + resp = make_response(redirect(dest)) |
| 121 | + resp.set_cookie( |
| 122 | + COOKIE_NAME, value, max_age=SESSION_TTL, httponly=True, secure=True, samesite="Lax" |
| 123 | + ) |
| 124 | + return resp |
| 125 | + |
| 126 | + |
| 127 | +@app.route("/auth/logout") |
| 128 | +def logout(): |
| 129 | + resp = make_response(redirect("/auth/login")) |
| 130 | + resp.delete_cookie(COOKIE_NAME) |
| 131 | + return resp |
0 commit comments