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
+2 -1
View File
@@ -40,4 +40,5 @@ yarn-error.log*
*.tsbuildinfo
next-env.d.ts
public/form
public/form
drizzle
+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 [];
}
}
+137 -8
View File
@@ -1,6 +1,6 @@
"use client";
import React, { useState, useTransition } from "react";
import React, { useState, useTransition, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
@@ -9,7 +9,15 @@ import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { updateForm } from "@/app/admin/form/actions";
import { Loader2, Save } from "lucide-react";
import { Loader2, Save, ChevronDown } from "lucide-react";
import { getGuildRoles, DiscordRole } from "@/app/actions/discord";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"
interface FormExtraClientProps {
form: {
@@ -17,6 +25,8 @@ interface FormExtraClientProps {
discordWebhookUrl: string | null;
discordWebhookTemplate: string | null;
discordWebhookUpdateTemplate: string | null;
allowedRoles?: string[] | null;
deniedRoles?: string[] | null;
};
}
@@ -25,8 +35,21 @@ export default function FormExtraClient({ form }: FormExtraClientProps) {
const [webhookUrl, setWebhookUrl] = useState(form.discordWebhookUrl || "");
const [webhookTemplate, setWebhookTemplate] = useState(form.discordWebhookTemplate || "");
const [webhookUpdateTemplate, setWebhookUpdateTemplate] = useState(form.discordWebhookUpdateTemplate || "");
const [allowedRoles, setAllowedRoles] = useState<string[]>(form.allowedRoles || []);
const [deniedRoles, setDeniedRoles] = useState<string[]>(form.deniedRoles || []);
const [roles, setRoles] = useState<DiscordRole[]>([]);
const [loadingRoles, setLoadingRoles] = useState(true);
const [isSaving, startSaveTransition] = useTransition();
useEffect(() => {
getGuildRoles()
.then(r => setRoles(r))
.catch(() => toast.error("Failed to load Discord roles."))
.finally(() => setLoadingRoles(false));
}, []);
const handleSave = () => {
startSaveTransition(async () => {
try {
@@ -34,6 +57,8 @@ export default function FormExtraClient({ form }: FormExtraClientProps) {
discordWebhookUrl: webhookUrl.trim() || null,
discordWebhookTemplate: webhookTemplate.trim() || null,
discordWebhookUpdateTemplate: webhookUpdateTemplate.trim() || null,
allowedRoles,
deniedRoles,
});
toast.success("Extra settings saved!");
router.refresh();
@@ -43,8 +68,111 @@ export default function FormExtraClient({ form }: FormExtraClientProps) {
});
};
const toggleRole = (list: string[], setList: (v: string[]) => void, roleId: string) => {
if (list.includes(roleId)) {
setList(list.filter(id => id !== roleId));
} else {
setList([...list, roleId]);
}
};
const renderRoleList = (list: string[], setList: (v: string[]) => void, label: string, desc: string) => {
const selectedRoles = roles.filter(r => list.includes(r.id));
return (
<div className="space-y-2 flex flex-col items-start">
<Label>{label}</Label>
<p className="text-sm text-muted-foreground mb-1">{desc}</p>
{loadingRoles ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" /> Loading roles...
</div>
) : (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full justify-between text-left">
<div className="flex flex-wrap gap-1">
{selectedRoles.length > 0 ? (
selectedRoles.map(role => {
const colorHex = role.color === 0 ? "#99aab5" : `#${role.color.toString(16).padStart(6, '0')}`;
return (
<div
key={role.id}
className="inline-flex items-center gap-1.5 rounded px-2 py-0.5 text-xs font-medium border"
style={{
backgroundColor: `${colorHex}1a`,
borderColor: `${colorHex}33`,
color: colorHex
}}
>
<div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: colorHex }} />
@{role.name}
</div>
);
})
) : (
<span className="text-muted-foreground my-auto">Select roles...</span>
)}
</div>
<ChevronDown className="w-4 h-4 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-78 min-w-(--radix-dropdown-menu-trigger-width) p-0">
<ScrollArea className="h-72 max-h-[calc(var(--radix-dropdown-menu-content-available-height)-2rem)]">
<div className="p-1">
{roles.map(role => {
const colorHex = role.color === 0 ? "#99aab5" : `#${role.color.toString(16).padStart(6, '0')}`;
return (
<DropdownMenuCheckboxItem
key={role.id}
checked={list.includes(role.id)}
onCheckedChange={() => toggleRole(list, setList, role.id)}
onSelect={(e) => e.preventDefault()}
>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full shrink-0" style={{ backgroundColor: colorHex }} />
<span className="text-sm">{role.name}</span>
</div>
</DropdownMenuCheckboxItem>
);
})}
{roles.length === 0 && (
<div className="p-2 text-sm text-muted-foreground text-center">No roles found.</div>
)}
</div>
</ScrollArea>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
);
};
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Access Control</CardTitle>
<CardDescription>
Restrict form access to specific Discord roles.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{renderRoleList(
allowedRoles,
setAllowedRoles,
"Allowed Roles",
"Users must have at least one of these roles to access the form. Leave empty to allow all."
)}
{renderRoleList(
deniedRoles,
setDeniedRoles,
"Denied Roles",
"Users with any of these roles will be blocked from accessing the form, even if they have an allowed role."
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Discord Webhook</CardTitle>
@@ -89,14 +217,15 @@ export default function FormExtraClient({ form }: FormExtraClientProps) {
Used when a user updates their existing submission. Use <code>{`{1}`}</code>, <code>{`{2}`}</code> for answers, and <code>{`{username}`}</code>, <code>{`{displayname}`}</code>, <code>{`{id}`}</code> for user info.
</p>
</div>
<div className="flex justify-end pt-2">
<Button onClick={handleSave} disabled={isSaving} className="gap-2">
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
Save Settings
</Button>
</div>
</CardContent>
</Card>
<div className="flex justify-end pt-2 pb-8">
<Button onClick={handleSave} disabled={isSaving} className="gap-2">
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
Save Settings
</Button>
</div>
</div>
);
}
+1 -1
View File
@@ -28,7 +28,7 @@ export async function createForm(formData: FormData) {
redirect(`/form/admin/${form.id}/edit`);
}
export async function updateForm(id: string, data: { title?: string; description?: string | null; isOpen?: boolean; discordWebhookUrl?: string | null; discordWebhookTemplate?: string | null; discordWebhookUpdateTemplate?: string | null }) {
export async function updateForm(id: string, data: { title?: string; description?: string | null; isOpen?: boolean; discordWebhookUrl?: string | null; discordWebhookTemplate?: string | null; discordWebhookUpdateTemplate?: string | null; allowedRoles?: string[]; deniedRoles?: string[] }) {
const session = await getServerSession(authOptions);
const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
const discordId = (session?.user as { discordId?: string } | undefined)?.discordId;
+24
View File
@@ -3,6 +3,7 @@ import { FormFillerClient } from "../client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { notFound } from "next/navigation";
import { getGuildMemberRoles } from "@/app/actions/discord";
export const dynamic = "force-dynamic";
@@ -23,6 +24,29 @@ export default async function FormsSubmitPage(
return notFound();
}
if (discordId) {
const allowedRoles = form.allowedRoles || [];
const deniedRoles = form.deniedRoles || [];
if (allowedRoles.length > 0 || deniedRoles.length > 0) {
const userRoles = await getGuildMemberRoles(discordId);
let isAllowed = allowedRoles.length === 0;
if (allowedRoles.length > 0) {
isAllowed = userRoles.some(r => allowedRoles.includes(r));
}
let isDenied = false;
if (deniedRoles.length > 0) {
isDenied = userRoles.some(r => deniedRoles.includes(r));
}
if (!isAllowed || isDenied) {
return notFound();
}
}
}
const questionsList = await db.query.questions.findMany({
where: (q, { eq }) => eq(q.formId, form.id),
orderBy: (q, { asc }) => [asc(q.displayOrder)],
+2
View File
@@ -21,6 +21,8 @@ export const forms = formSchema.table("form", {
discordWebhookUrl: text("discord_webhook_url"),
discordWebhookTemplate: text("discord_webhook_template"),
discordWebhookUpdateTemplate: text("discord_webhook_update_template"),
allowedRoles: jsonb("allowed_roles").$type<string[]>().default([]),
deniedRoles: jsonb("denied_roles").$type<string[]>().default([]),
});
export type QuestionType = "text" | "textarea" | "radio" | "checkbox";
+7
View File
@@ -71,6 +71,13 @@
"when": 1782731954122,
"tag": "0009_slippery_nomad",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1783089081925,
"tag": "0010_rainy_speedball",
"breakpoints": true
}
]
}