You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What im trying to do & the issue:
Hey! im currently trying to make a Dashboard for my Discord Bot. For authentication purposes i need to verify that the user has has access to specific guilds. For that i use session.guilds to save the guilds in there which the user should have access to. The problem i have is that if i try to get the session.guilds again the value i put in there is gone.
Code reference:
Here i define my authOptions
// app/api/auth/[...nextauth]/route.jsimportNextAuthfrom'next-auth';importDiscordProviderfrom'next-auth/providers/discord';exportconstauthOptions={providers: [DiscordProvider({clientId: process.env.DISCORD_CLIENT_ID,clientSecret: process.env.DISCORD_CLIENT_SECRET,authorization: {params: {scope: 'identify guilds',// Scopes you want to request},},}),],secret: process.env.NEXTAUTH_SECRET,callbacks: {asyncjwt({ token, account }){// Save access tokenif(account){token.accessToken=account.access_token;token.guilds=user?.guilds||[];}returntoken;},asyncsession({ session, token }){// Attach access token to sessionsession.accessToken=token.accessToken;session.guilds=token.guilds||[];returnsession;},},};consthandler=NextAuth(authOptions);export{handlerasGET,handlerasPOST};
Here i get the guilds a user should have access to and add them to the session using session.guilds = mutualGuilds;.
// app/api/getGuilds/route.jsimport{NextResponse}from'next/server';import{getServerSession}from"next-auth";import{authOptions}from'../auth/[...nextauth]/route';exportasyncfunctionGET(req){console.log('Fetching guilds...');constaccessToken=req.headers.get('Authorization');if(!accessToken){console.error('Authorization token not provided.');returnNextResponse.json({error: 'Authorization token is required'},{status: 401});}try{// Get user guildsconstuserResponse=awaitfetch('https://discord.com/api/users/@me/guilds',{headers: {Authorization: accessToken,},});if(!userResponse.ok){console.error('Failed to fetch user guilds:',userResponse.statusText);returnNextResponse.json({error: 'Failed to fetch user guilds'},{status: userResponse.status});}constuserGuilds=awaituserResponse.json();// Filter user guilds where user has administrator permissionsconstadminGuilds=userGuilds.filter((guild)=>{return(guild.permissions&0x8)===0x8;// Check if the administrator permission is set});// Get bot guildsconstbotResponse=awaitfetch('https://discord.com/api/v9/users/@me/guilds',{headers: {Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,},});if(!botResponse.ok){console.error('Failed to fetch bot guilds:',botResponse.statusText);returnNextResponse.json({error: 'Failed to fetch bot guilds'},{status: botResponse.status});}constbotGuilds=awaitbotResponse.json();// Find guilds where both the user is an admin and the bot is in the guildconstmutualGuilds=adminGuilds.filter(userGuild=>botGuilds.some(botGuild=>botGuild.id===userGuild.id));constsession=awaitgetServerSession(authOptions);session.guilds=mutualGuilds;console.log(session);returnNextResponse.json(mutualGuilds);}catch(error){console.error('An error occurred while fetching guilds:',error);returnNextResponse.json({error: 'Failed to retrieve guilds.'},{status: 500});}}
The console.log outputs the following (some values changed for privacy):
and then i try to read the value so i can verify that the user has access to this guild. but here the console.log output shows [] so it somehow did not take over the values ive set...
// app/dashboard/[id]/page.jsimport{getServerSession}from"next-auth";import{authOptions}from'../../api/auth/[...nextauth]/route';import{redirect}from'next/navigation';exportdefaultasyncfunctionGuildPage({ params }){// the authorized id is id: 1244951898239275061const{ id }=params;// returns 1244951898239275061constsession=awaitgetServerSession(authOptions);console.log('User Guilds:',JSON.stringify(session.guilds,null,2));constisAuthorized=session.guilds.some(guild=>guild.id===id);if(!isAuthorized){redirect('/dashboard');}return(<div><h1>Guild ID: {id}</h1></div>);}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
What im trying to do & the issue:
Hey! im currently trying to make a Dashboard for my Discord Bot. For authentication purposes i need to verify that the user has has access to specific guilds. For that i use session.guilds to save the guilds in there which the user should have access to. The problem i have is that if i try to get the session.guilds again the value i put in there is gone.
Code reference:
Here i define my authOptions
Here i get the guilds a user should have access to and add them to the session using
session.guilds = mutualGuilds;
.The console.log outputs the following (some values changed for privacy):
and then i try to read the value so i can verify that the user has access to this guild. but here the console.log output shows
[]
so it somehow did not take over the values ive set...Beta Was this translation helpful? Give feedback.
All reactions