Created
February 23, 2023 08:53
-
-
Save musaprg/03320ad7ddd19a900631a270854a095f to your computer and use it in GitHub Desktop.
Auth0 Action for the Discord Guild Member Authorization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Client, Intents } = require('discord.js'); | |
/** | |
* Handler that will be called during the execution of a PostLogin flow. | |
* | |
* @param {Event} event - Details about the user and the context in which they are logging in. | |
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login. | |
*/ | |
exports.onExecutePostLogin = async (event, api) => { | |
const identities = event.user.identities.filter((v) => { return v.connection == "discord"; }); | |
const identity = identities.length == 1 ? identities[0] : null; | |
if (!identity) { | |
api.access.deny("this user isn't authenticated with discord"); | |
return; | |
} | |
const result = identity.user_id?.match(/discord\|(.+)/); | |
if (result?.length != 2) { | |
api.access.deny("the format of user_id is invalid"); | |
} | |
const userID = result?.length == 2 ? result[1] : null; | |
const client = new Client({ intents: [Intents.FLAGS.GUILDS] }); | |
client.login(event.secrets.DISCORD_BOT_TOKEN); | |
const isUserMember = await client.guilds.fetch(event.secrets.DISCORD_GUILD_ID) | |
.then((guild) => { | |
return guild.members.fetch(userID) | |
.then(() => { return true; }) | |
.catch((e) => { console.warn(e); }); // TODO(musaprg): do better error handling | |
}); | |
if (!isUserMember) { | |
api.access.deny("You are not a member of the Miscord. Please contact the administrator for details."); | |
return; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment