feat: add Discord role-based access control for forms with custom dropdown UI

This commit is contained in:
2026-07-03 21:58:10 +07:00 Unverified
parent a0eac6ce1e
commit 10162c9363
7 changed files with 236 additions and 10 deletions
+63
View File
@@ -0,0 +1,63 @@
"use server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
export interface DiscordRole {
id: string;
name: string;
color: number;
position: number;
}
export async function getGuildRoles(): Promise<DiscordRole[]> {
const token = process.env.DISCORD_BOT_TOKEN;
const guildId = process.env.DISCORD_GUILD_ID;
if (!token || !guildId) return [];
const session = await getServerSession(authOptions);
const discordId = (session?.user as any)?.discordId;
const admins = (process.env.ADMIN_DISCORD_IDS || "").split(",");
if (!discordId || !admins.includes(discordId)) {
throw new Error("Unauthorized");
}
try {
const res = await fetch(`https://discord.com/api/v10/guilds/${guildId}/roles`, {
headers: { Authorization: `Bot ${token}` },
next: { revalidate: 60 }, // Cache for 60s
});
if (!res.ok) return [];
const roles: any[] = await res.json();
return roles.map(r => ({
id: r.id,
name: r.name,
color: r.color,
position: r.position,
})).sort((a, b) => b.position - a.position);
} catch {
return [];
}
}
export async function getGuildMemberRoles(discordId: string): Promise<string[]> {
const token = process.env.DISCORD_BOT_TOKEN;
const guildId = process.env.DISCORD_GUILD_ID;
if (!token || !guildId || !discordId) return [];
try {
const res = await fetch(`https://discord.com/api/v10/guilds/${guildId}/members/${discordId}`, {
headers: { Authorization: `Bot ${token}` },
cache: "no-store", // Always fresh for access control
});
if (!res.ok) return [];
const member = await res.json();
return member.roles || [];
} catch {
return [];
}
}