From d018fbb1d64dfbd136838f34f87ac4ea93fc809d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jozef=20Steinh=C3=BCbl?= Date: Fri, 2 Aug 2024 23:43:42 +0200 Subject: [PATCH] feat: fetch guilds --- apps/website/auth.config.ts | 56 +++++++++++++------- apps/website/src/env.d.ts | 8 +++ apps/website/src/pages/dashboard/index.astro | 9 +++- 3 files changed, 53 insertions(+), 20 deletions(-) diff --git a/apps/website/auth.config.ts b/apps/website/auth.config.ts index 140c417..8223e6f 100644 --- a/apps/website/auth.config.ts +++ b/apps/website/auth.config.ts @@ -2,22 +2,42 @@ import Discord from "@auth/core/providers/discord"; import { defineConfig } from "auth-astro"; export default defineConfig({ - providers: [ - Discord({ - clientId: import.meta.env.DISCORD_CLIENT_ID, - clientSecret: import.meta.env.DISCORD_CLIENT_SECRET, - }), - ], - callbacks: { - session({ session, token }) { - if (session.user && token?.sub) { - session.user.id = token.sub; - } - return session; - }, - }, - pages: { - signIn: "/auth/login", - signOut: "/auth/logout", - }, + providers: [ + Discord({ + clientId: import.meta.env.DISCORD_CLIENT_ID, + clientSecret: import.meta.env.DISCORD_CLIENT_SECRET, + authorization: + "https://discord.com/api/oauth2/authorize?scope=guilds+identify+email", + }), + ], + callbacks: { + async jwt({ token, account, profile }) { + if (account && profile) { + token.accessToken = account.access_token; + token.id = profile.id; + } + + return token; + }, + async session({ session, token }) { + if (session.user) { + session.user.id = token.id as string; + + const guilds = await fetch("https://discord.com/api/users/@me/guilds", { + headers: { + Authorization: `Bearer ${token.accessToken as string}`, + "Cache-Control": "max-age=300", + }, + }); + + session.user.guilds = await guilds.json(); + } + + return session; + }, + }, + pages: { + signIn: "/auth/login", + signOut: "/auth/logout", + }, }); diff --git a/apps/website/src/env.d.ts b/apps/website/src/env.d.ts index f964fe0..2fe3396 100644 --- a/apps/website/src/env.d.ts +++ b/apps/website/src/env.d.ts @@ -1 +1,9 @@ /// + +import type { User as AuthCoreUser } from "@auth/core/types"; + +export type User = AuthCoreUser & { + guilds: { + name: string; + }[]; +}; diff --git a/apps/website/src/pages/dashboard/index.astro b/apps/website/src/pages/dashboard/index.astro index cbb93ab..a80f808 100644 --- a/apps/website/src/pages/dashboard/index.astro +++ b/apps/website/src/pages/dashboard/index.astro @@ -1,10 +1,15 @@ --- +import type { User } from "~/env"; import { getSession } from "auth-astro/server"; const session = await getSession(Astro.request); -if (!session) { +if (!session || !session.user) { return Astro.redirect("/auth/login"); } + +const user = session.user as User; +console.log(user.guilds[0]); --- -

Welcome {session.user?.name}

+

Welcome {user.name}

+{user.guilds.map((g) => g.id).join("\n\n")}