SignIn discord user if he is on a certain Server

Hi im wondering if there is a way in NextAuth to sign user only if they are on a specific server otherswise redirect them to signin page
4 Replies
jeromemarshall
you can use the signin callback in the nextauth options to achieve this
barry
barry2y ago
Next auth is shit at this, you'd need to query your db to get said account from the Account table, in there you need to get the access_token, which you need to use to get the bearer_token which you then can use to use the discord api You'd have to implement this yourself It's doable with nextauth but sounds annoying lol
H
H2y ago
yea that what i did
async signIn({ user, account }) {
if (account?.provider === "discord") {
const data = await fetch(
"https://discordapp.com/api/users/@me/guilds",
{
headers: {
Authorization: `Bearer ${account?.access_token as string}`,
"Content-Type": "application/json",
},
}
).then(async (res) => (await res.json()) as { id: string }[]);
if (data.some((guild) => guild.id === env.SERVER_GUILD_ID)) {
return true;
} else {
return "/signin?error=AccessDenied";
}
}
// code...
async signIn({ user, account }) {
if (account?.provider === "discord") {
const data = await fetch(
"https://discordapp.com/api/users/@me/guilds",
{
headers: {
Authorization: `Bearer ${account?.access_token as string}`,
"Content-Type": "application/json",
},
}
).then(async (res) => (await res.json()) as { id: string }[]);
if (data.some((guild) => guild.id === env.SERVER_GUILD_ID)) {
return true;
} else {
return "/signin?error=AccessDenied";
}
}
// code...
looks horrible but it works
jeromemarshall
ikr, sometimes you cant help it but hack your way through
Want results from more Discord servers?
Add your server