From 234518a62ecadb9ff97e57afe1b2b1c8a902bd60 Mon Sep 17 00:00:00 2001 From: NotNite Date: Tue, 25 Apr 2023 21:23:55 -0400 Subject: [PATCH] use discord avatar as fallback --- src/app/api/register/route.ts | 11 +++++++++++ src/app/oauth/discord/oauth.ts | 16 ++++++++++++++++ src/app/register/RegisterForm.tsx | 5 ++++- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/app/api/register/route.ts b/src/app/api/register/route.ts index bc69d52..361b619 100644 --- a/src/app/api/register/route.ts +++ b/src/app/api/register/route.ts @@ -1,6 +1,7 @@ import * as ldap from "@/ldap"; import prisma from "@/prisma"; import { getUserFromRequest } from "@/auth"; +import { getDiscordAvatar } from "@/app/oauth/discord/oauth"; type RequestBody = { username: string; @@ -67,6 +68,16 @@ export async function POST(request: Request) { } } + const discordAuth = await prisma.discordAuth.findFirst({ + where: { + userId: user.id + } + }); + + if (discordAuth !== null && avatarBuf === undefined) { + avatarBuf = await getDiscordAvatar(discordAuth.accessToken); + } + const users = await ldap.getUsers(); for (const user of users) { if (user.id.toLowerCase() === username.toLowerCase()) { diff --git a/src/app/oauth/discord/oauth.ts b/src/app/oauth/discord/oauth.ts index 0f0e65a..d8e10e3 100644 --- a/src/app/oauth/discord/oauth.ts +++ b/src/app/oauth/discord/oauth.ts @@ -10,6 +10,7 @@ export type DiscordAccessTokenResponse = { export type DiscordUserResponse = { id: string; + avatar: string; }; export type DiscordGuildResponse = { @@ -39,3 +40,18 @@ export async function getDiscordGuilds(token: string) { const res: DiscordGuildResponse[] = await req.json(); return res.map((guild) => guild.id); } + +export async function getDiscordAvatar(token: string) { + const req = await fetch("https://discord.com/api/users/@me", { + headers: { + Authorization: `Bearer ${token}` + } + }); + + const res: DiscordUserResponse = await req.json(); + const file = `https://cdn.discordapp.com/avatars/${res.id}/${res.avatar}.png`; + + const avatarReq = await fetch(file); + const avatarBuffer = await avatarReq.arrayBuffer(); + return Buffer.from(avatarBuffer); +} diff --git a/src/app/register/RegisterForm.tsx b/src/app/register/RegisterForm.tsx index 100b558..5cf0f75 100644 --- a/src/app/register/RegisterForm.tsx +++ b/src/app/register/RegisterForm.tsx @@ -184,7 +184,10 @@ export default function RegisterForm({ ticket }: { ticket: string }) { />