64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
"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 [];
|
|
}
|
|
}
|