feat(form) : force user to join discord server
This commit is contained in:
@@ -4,6 +4,7 @@ import { DrizzleAdapter } from "@auth/drizzle-adapter";
|
||||
import { db } from "@/db";
|
||||
import { accounts, sessions, users, verificationTokens } from "@/db/schema";
|
||||
import type { SessionWithDiscord } from "@/lib/auth";
|
||||
import { addDiscordGuildMember } from "@/lib/discord";
|
||||
|
||||
const discordIdCache = new Map<string, string>();
|
||||
|
||||
@@ -18,9 +19,21 @@ export const authOptions: NextAuthOptions = {
|
||||
DiscordProvider({
|
||||
clientId: process.env.DISCORD_CLIENT_ID!,
|
||||
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
|
||||
authorization: {
|
||||
params: {
|
||||
scope: "identify email guilds.join",
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async signIn({ account }) {
|
||||
if (account?.provider === "discord" && account.providerAccountId && account.access_token) {
|
||||
await addDiscordGuildMember(account.providerAccountId, account.access_token);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
async session({ session, user }) {
|
||||
if (session.user) {
|
||||
(session as SessionWithDiscord).user!.id = user.id;
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { addDiscordGuildMember } from "@/lib/discord";
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalBotToken = process.env.DISCORD_BOT_TOKEN;
|
||||
const originalGuildId = process.env.DISCORD_GUILD_ID;
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalBotToken === undefined) {
|
||||
delete process.env.DISCORD_BOT_TOKEN;
|
||||
} else {
|
||||
process.env.DISCORD_BOT_TOKEN = originalBotToken;
|
||||
}
|
||||
if (originalGuildId === undefined) {
|
||||
delete process.env.DISCORD_GUILD_ID;
|
||||
} else {
|
||||
process.env.DISCORD_GUILD_ID = originalGuildId;
|
||||
}
|
||||
});
|
||||
|
||||
function mockFetch(handler: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>) {
|
||||
globalThis.fetch = handler as unknown as typeof fetch;
|
||||
}
|
||||
|
||||
describe("Discord guild member join", () => {
|
||||
test("adds a member with the OAuth access token", async () => {
|
||||
process.env.DISCORD_BOT_TOKEN = "bot-token";
|
||||
process.env.DISCORD_GUILD_ID = "guild-1";
|
||||
|
||||
mockFetch(async (input, init) => {
|
||||
expect(input).toBe("https://discord.com/api/v10/guilds/guild-1/members/user-1");
|
||||
expect(init?.method).toBe("PUT");
|
||||
expect(init?.headers).toEqual({
|
||||
Authorization: "Bot bot-token",
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
expect(init?.body).toBe(JSON.stringify({ access_token: "oauth-token" }));
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
|
||||
await expect(addDiscordGuildMember("user-1", "oauth-token")).resolves.toBeTrue();
|
||||
});
|
||||
|
||||
test("uses the configured Erika guild by default", async () => {
|
||||
process.env.DISCORD_BOT_TOKEN = "bot-token";
|
||||
delete process.env.DISCORD_GUILD_ID;
|
||||
|
||||
mockFetch(async (input) => {
|
||||
expect(input).toBe("https://discord.com/api/v10/guilds/1302977523310923847/members/user-1");
|
||||
return new Response(null, { status: 201 });
|
||||
});
|
||||
|
||||
await expect(addDiscordGuildMember("user-1", "oauth-token")).resolves.toBeTrue();
|
||||
});
|
||||
|
||||
test("does not call Discord when tokens are missing", async () => {
|
||||
delete process.env.DISCORD_BOT_TOKEN;
|
||||
process.env.DISCORD_GUILD_ID = "guild-1";
|
||||
|
||||
let called = false;
|
||||
mockFetch(async () => {
|
||||
called = true;
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
|
||||
await expect(addDiscordGuildMember("user-1", "oauth-token")).resolves.toBeFalse();
|
||||
expect(called).toBeFalse();
|
||||
});
|
||||
});
|
||||
+40
-3
@@ -23,18 +23,55 @@ interface CacheEntry<T> {
|
||||
const rolesCache: { entry: CacheEntry<DiscordRole[]> | null } = { entry: null };
|
||||
const profileCache = new Map<string, CacheEntry<DiscordMemberProfile>>();
|
||||
const CACHE_TTL = 60_000;
|
||||
const DEFAULT_DISCORD_GUILD_ID = "1302977523310923847";
|
||||
|
||||
function getCached<T>(entry: CacheEntry<T> | null | undefined): T | null {
|
||||
if (entry && Date.now() < entry.expiresAt) return entry.data;
|
||||
return null;
|
||||
}
|
||||
|
||||
function getDiscordGuildId() {
|
||||
return process.env.DISCORD_GUILD_ID || DEFAULT_DISCORD_GUILD_ID;
|
||||
}
|
||||
|
||||
export async function addDiscordGuildMember(discordId: string, accessToken: string): Promise<boolean> {
|
||||
const token = process.env.DISCORD_BOT_TOKEN;
|
||||
const guildId = getDiscordGuildId();
|
||||
if (!token || !guildId || !discordId || !accessToken) return false;
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
`https://discord.com/api/v10/guilds/${encodeURIComponent(guildId)}/members/${encodeURIComponent(discordId)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bot ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ access_token: accessToken }),
|
||||
signal: AbortSignal.timeout(5000),
|
||||
},
|
||||
);
|
||||
|
||||
if (res.status === 201 || res.status === 204) return true;
|
||||
|
||||
const body = await res.text().catch(() => "");
|
||||
console.error(
|
||||
`Failed to add Discord member ${discordId} to guild ${guildId}: ${res.status}${body ? ` ${body.slice(0, 300)}` : ""}`,
|
||||
);
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.error(`Failed to add Discord member ${discordId} to guild ${guildId}`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGuildRolesInternal(): Promise<DiscordRole[]> {
|
||||
const cached = getCached(rolesCache.entry);
|
||||
if (cached) return cached;
|
||||
|
||||
const token = process.env.DISCORD_BOT_TOKEN;
|
||||
const guildId = process.env.DISCORD_GUILD_ID;
|
||||
const guildId = getDiscordGuildId();
|
||||
if (!token || !guildId) return [];
|
||||
|
||||
try {
|
||||
@@ -69,7 +106,7 @@ export async function getGuildRolesInternal(): Promise<DiscordRole[]> {
|
||||
|
||||
export async function getGuildMemberRoles(discordId: string): Promise<string[]> {
|
||||
const token = process.env.DISCORD_BOT_TOKEN;
|
||||
const guildId = process.env.DISCORD_GUILD_ID;
|
||||
const guildId = getDiscordGuildId();
|
||||
if (!token || !guildId || !discordId) return [];
|
||||
|
||||
try {
|
||||
@@ -93,7 +130,7 @@ export async function getDiscordMemberProfile(discordId: string): Promise<Discor
|
||||
if (cached) return cached;
|
||||
|
||||
const token = process.env.DISCORD_BOT_TOKEN;
|
||||
const guildId = process.env.DISCORD_GUILD_ID;
|
||||
const guildId = getDiscordGuildId();
|
||||
if (!token || !guildId || !discordId) return null;
|
||||
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user