Skip to content

Commit

Permalink
Added dynamic redirect URLs for Discord auth
Browse files Browse the repository at this point in the history
  • Loading branch information
slmnio committed Oct 12, 2022
1 parent 334c6cc commit 8f30b75
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
3 changes: 3 additions & 0 deletions server/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ DISCORD_TOKEN=
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=

DISCORD_REDIRECT_URI=http://localhost:8080/auth/discord/return # NOTE: only use this as an override, use domains otherwise
DISCORD_REDIRECT_DOMAINS=http://localhost:8080,https://dev.slmn.gg,https://slmn.gg

STAFFAPPS_GUILD_ID=
STAFFAPPS_CATEGORY_ID=
STAFFAPPS_APPLICATION_CHANNEL_ID=
Expand Down
14 changes: 11 additions & 3 deletions server/src/discord/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ function discordEnvSet() {
return ["DISCORD_CLIENT_ID", "DISCORD_CLIENT_SECRET", "DISCORD_REDIRECT_URI"].every(key => !!process.env[key]);
}

function getRequestingDomain(origin) {
// check it against our list
let domains = (process.env.DISCORD_REDIRECT_DOMAINS || "").split(",");

if (domains.includes(origin)) return origin;
return "https://dev.slmn.gg";
}

module.exports = ({ app, router, cors, Cache, io }) => {
if (!discordEnvSet()) return console.warn("Discord authentication on the server is disabled. Set DISCORD_ keys in server/.env to enable it.");

Expand All @@ -18,7 +26,7 @@ module.exports = ({ app, router, cors, Cache, io }) => {
const code = req.body?.code;
if (!code) return res.status(400).send({ error: true, message: "No code sent to SLMN.GG server for Discord auth" });

let tokens = await getToken(code);
let tokens = await getToken(code, getRequestingDomain(req.headers?.origin));

if (tokens.error) {
return res.send({
Expand Down Expand Up @@ -84,13 +92,13 @@ module.exports = ({ app, router, cors, Cache, io }) => {

app.use("/auth", authApp);

async function getToken(code) {
async function getToken(code, origin) {

// console.log("ZOOM DISCORD TIME");
const data = {
client_id: process.env.DISCORD_CLIENT_ID,
client_secret: process.env.DISCORD_CLIENT_SECRET,
redirect_uri: process.env.DISCORD_REDIRECT_URI, // TODO: use request data to use request domain
redirect_uri: process.env.DISCORD_REDIRECT_URI || `${origin}/auth/discord/return`,
grant_type: "authorization_code",
code: code,
scope: "identify"
Expand Down

0 comments on commit 8f30b75

Please sign in to comment.