Update configuration and README for improved setup and security; disable default API and emoji sync, and enhance Discord permission checks in API routes.
This commit is contained in:
@@ -1,20 +1,24 @@
|
||||
# API URL for the dashboard backend
|
||||
NEXT_PUBLIC_API_URL=https://xxxx-xxxx-xxxx.ngrok-free.app/api/v1
|
||||
# Bot API URL (server-side — used by Next.js proxy and SSR)
|
||||
DASHBOARD_API_URL=http://127.0.0.1:8000/api/v1
|
||||
|
||||
# API Key for authentication (if used)
|
||||
NEXT_PUBLIC_DASHBOARD_API_KEY=ZYROX_SECURE_API_KEY_12345_CHANGE_THIS_ASAP_BY_CODEX_DEVS
|
||||
# Bot API key (SERVER ONLY — never use NEXT_PUBLIC_ prefix)
|
||||
DASHBOARD_API_KEY=generate_a_long_random_secret_here
|
||||
|
||||
# Legacy/public API URL (optional fallback for DASHBOARD_API_URL)
|
||||
NEXT_PUBLIC_API_URL=http://127.0.0.1:8000/api/v1
|
||||
|
||||
# NextAuth Configuration
|
||||
NEXTAUTH_URL=https://your-vercel-url-here-codex-devs.vercel.app/
|
||||
NEXTAUTH_SECRET=zyrox_nextauth_default_secret_string_2026_change_me_BY_CODEX_DEVS
|
||||
NEXTAUTH_URL=http://localhost:3000/
|
||||
NEXTAUTH_SECRET=generate_a_long_random_secret_here
|
||||
|
||||
# Discord OAuth configuration
|
||||
DISCORD_CLIENT_ID=
|
||||
DISCORD_CLIENT_SECRET=
|
||||
|
||||
# Admin User IDs (comma separated)
|
||||
NEXT_PUBLIC_ADMIN_IDS=870179991462236170
|
||||
# Dashboard admin user IDs (comma separated — your Discord user ID)
|
||||
ADMIN_IDS=YOUR_DISCORD_USER_ID_HERE
|
||||
NEXT_PUBLIC_ADMIN_IDS=YOUR_DISCORD_USER_ID_HERE
|
||||
|
||||
# Customizable Brand / Bot name shown across the dashboard
|
||||
NEXT_PUBLIC_BRAND_NAME="ZyroX"
|
||||
NEXT_PUBLIC_BRAND_NAME_WORD="ZX"
|
||||
NEXT_PUBLIC_BRAND_NAME_WORD="ZX"
|
||||
|
||||
@@ -1,89 +1,34 @@
|
||||
<div align="center">
|
||||
|
||||
```
|
||||
███████╗██╗ ██╗██████╗ ██████╗ ██╗ ██╗
|
||||
╚══███╔╝╚██╗ ██╔╝██╔══██╗██╔═══██╗╚██╗██╔╝
|
||||
███╔╝ ╚████╔╝ ██████╔╝██║ ██║ ╚███╔╝
|
||||
███╔╝ ╚██╔╝ ██╔══██╗██║ ██║ ██╔██╗
|
||||
███████╗ ██║ ██║ ██║╚██████╔╝██╔╝ ██╗
|
||||
╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
|
||||
```
|
||||
# ZyroX Dashboard
|
||||
|
||||
<h3>ZyroX Dashboard — Next.js Web Interface</h3>
|
||||
|
||||
<a href="https://nexiohost.in"><img src="https://img.shields.io/badge/⭐%20PREMIUM%20HOSTING-NexioHost-FFD700?style=for-the-badge&labelColor=1a1a2e&color=FFD700&logoColor=FFD700"/></a>
|
||||
|
||||
<p>
|
||||
<a href="https://nextjs.org"><img src="https://img.shields.io/badge/Next.js-14+-000000?style=for-the-badge&logo=nextdotjs&logoColor=white"/></a>
|
||||
<a href="https://typescriptlang.org"><img src="https://img.shields.io/badge/TypeScript-5+-3178C6?style=for-the-badge&logo=typescript&logoColor=white"/></a>
|
||||
<a href="https://tailwindcss.com"><img src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=for-the-badge&logo=tailwindcss&logoColor=white"/></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-red?style=for-the-badge"/></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://discord.gg/codexdev"><img src="https://img.shields.io/badge/Discord-Join_Server-5865F2?style=for-the-badge&logo=discord&logoColor=white"/></a>
|
||||
<a href="https://youtube.com/@CodeXDevs"><img src="https://img.shields.io/badge/YouTube-CodeXDevs-FF0000?style=for-the-badge&logo=youtube&logoColor=white"/></a>
|
||||
<a href="https://github.com/RayExo"><img src="https://img.shields.io/badge/GitHub-RayExo-181717?style=for-the-badge&logo=github&logoColor=white"/></a>
|
||||
</p>
|
||||
Next.js web dashboard for configuring the ZyroX Discord bot.
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## ✦ Overview
|
||||
## Overview
|
||||
|
||||
This folder contains the ZyroX web dashboard built with `Next.js 14` (App Router), `TypeScript`, and `Tailwind CSS`. It connects to the bot's FastAPI backend via a permanent Cloudflare Tunnel HTTPS URL and lets server admins manage all bot settings through a sleek, branded UI.
|
||||
|
||||
```
|
||||
dashboard/
|
||||
├── app/ App Router pages & API routes
|
||||
│ ├── api/auth/ NextAuth OAuth callback
|
||||
│ ├── dashboard/ Main dashboard area
|
||||
│ │ ├── admin/ Admin-only panel
|
||||
│ │ ├── guilds/ Server selection
|
||||
│ │ └── guild/[guildId]/ Per-server settings pages
|
||||
│ │ ├── antinuke/
|
||||
│ │ ├── automod/
|
||||
│ │ ├── leveling/
|
||||
│ │ ├── logging/
|
||||
│ │ ├── tickets/
|
||||
│ │ ├── welcome/
|
||||
│ │ └── …more
|
||||
│ ├── docs/ Documentation page
|
||||
│ ├── privacy/ Privacy policy
|
||||
│ └── terms/ Terms of service
|
||||
├── components/
|
||||
│ ├── dashboard/ Feature-specific form components
|
||||
│ └── ui/ Base UI components (button, card, input…)
|
||||
├── hooks/ Custom React hooks
|
||||
├── lib/ API client, auth config, utilities
|
||||
└── types/ TypeScript type definitions
|
||||
```
|
||||
- **Discord OAuth login** — users only see servers they can manage
|
||||
- **Server-side API proxy** — `DASHBOARD_API_KEY` never exposed to the browser
|
||||
- **Guild permission checks** — bot API verifies Discord Manage Server / Admin rights
|
||||
- **Fully branded** — name and colours via environment variables
|
||||
- **Vercel-ready**
|
||||
|
||||
---
|
||||
|
||||
## ✦ Features
|
||||
|
||||
- **Discord OAuth2 login** — secure sign-in, session managed by NextAuth
|
||||
- **Per-server management** — antinuke, automod, leveling, logging, tickets, welcome, and more
|
||||
- **Live bot stats** — real-time metrics pulled from the FastAPI backend
|
||||
- **Admin panel** — owner-only configuration and announcements
|
||||
- **Fully branded** — name, logo, and colours via environment variables
|
||||
- **HTTPS ready** — connects to the bot's permanent Cloudflare Tunnel URL
|
||||
- **Vercel-ready** — deploys in minutes with zero config changes
|
||||
|
||||
---
|
||||
|
||||
## ✦ Prerequisites
|
||||
## Prerequisites
|
||||
|
||||
| Requirement | Notes |
|
||||
|---|---|
|
||||
| Node.js 18+ | — |
|
||||
| ZyroX bot running | with `API_ENABLED=true` and `TUNNEL_ENABLED=true` |
|
||||
| ZyroX bot running | with `API_ENABLED=true` on `127.0.0.1` (or via Cloudflare Tunnel) |
|
||||
| Discord OAuth app | from [Discord Developer Portal](https://discord.com/developers/applications) |
|
||||
|
||||
---
|
||||
|
||||
## ✦ Setup
|
||||
## Setup
|
||||
|
||||
### 1 — Install dependencies
|
||||
|
||||
@@ -93,23 +38,23 @@ npm install
|
||||
|
||||
### 2 — Configure environment
|
||||
|
||||
Create a `.env.local` file in this folder:
|
||||
Create `.env.local` in this folder (see `.env.example`):
|
||||
|
||||
```env
|
||||
# ── Bot API ───────────────────────────────────────────────────────
|
||||
# Use the Cloudflare Tunnel URL from the bot's console output
|
||||
NEXT_PUBLIC_API_URL = https://api.yourdomain.com/api/v1
|
||||
NEXT_PUBLIC_DASHBOARD_API_KEY = your_shared_api_key # must match bot's DASHBOARD_API_KEY
|
||||
# ── Bot API (server-side only — never use NEXT_PUBLIC_ for the key) ──
|
||||
DASHBOARD_API_URL = http://127.0.0.1:8000/api/v1
|
||||
DASHBOARD_API_KEY = same_secret_as_bot_DASHBOARD_API_KEY
|
||||
|
||||
# ── NextAuth ──────────────────────────────────────────────────────
|
||||
NEXTAUTH_URL = http://localhost:3000
|
||||
NEXTAUTH_SECRET = a_long_random_string # generate: openssl rand -base64 32
|
||||
NEXTAUTH_SECRET = a_long_random_string
|
||||
|
||||
# ── Discord OAuth ─────────────────────────────────────────────────
|
||||
DISCORD_CLIENT_ID = your_discord_oauth_client_id
|
||||
DISCORD_CLIENT_SECRET = your_discord_oauth_client_secret
|
||||
|
||||
# ── Branding ──────────────────────────────────────────────────────
|
||||
# ── Admin & Branding ──────────────────────────────────────────────
|
||||
ADMIN_IDS = your_discord_user_id
|
||||
NEXT_PUBLIC_ADMIN_IDS = your_discord_user_id
|
||||
NEXT_PUBLIC_BRAND_NAME = "ZyroX"
|
||||
NEXT_PUBLIC_BRAND_NAME_WORD = "ZX"
|
||||
@@ -125,102 +70,64 @@ Open [http://localhost:3000](http://localhost:3000)
|
||||
|
||||
---
|
||||
|
||||
## ✦ Environment Reference
|
||||
## Environment Reference
|
||||
|
||||
| Variable | Description |
|
||||
|---|---|
|
||||
| `NEXT_PUBLIC_API_URL` | Full URL to the bot's FastAPI backend — use the Cloudflare Tunnel URL |
|
||||
| `NEXT_PUBLIC_DASHBOARD_API_KEY` | Must exactly match `DASHBOARD_API_KEY` in the bot `.env` |
|
||||
| `NEXTAUTH_URL` | Your dashboard's public URL (Vercel domain in production) |
|
||||
| `DASHBOARD_API_URL` | Bot API URL (server-side). Local: `http://127.0.0.1:8000/api/v1` |
|
||||
| `DASHBOARD_API_KEY` | Must match bot `DASHBOARD_API_KEY` — **server-side only** |
|
||||
| `NEXTAUTH_URL` | Dashboard public URL |
|
||||
| `NEXTAUTH_SECRET` | Random secret for NextAuth session signing |
|
||||
| `DISCORD_CLIENT_ID` | Discord OAuth2 client ID |
|
||||
| `DISCORD_CLIENT_SECRET` | Discord OAuth2 client secret |
|
||||
| `NEXT_PUBLIC_ADMIN_IDS` | Comma-separated Discord user IDs with admin panel access |
|
||||
| `NEXT_PUBLIC_BRAND_NAME` | Bot name shown in the dashboard UI |
|
||||
| `NEXT_PUBLIC_BRAND_NAME_WORD` | Short abbreviation shown in the dashboard (e.g. `ZX`) |
|
||||
| `ADMIN_IDS` | Server-side admin user IDs (for admin API routes) |
|
||||
| `NEXT_PUBLIC_ADMIN_IDS` | Same IDs for admin panel UI visibility |
|
||||
| `NEXT_PUBLIC_BRAND_NAME` | Bot name in the dashboard UI |
|
||||
| `NEXT_PUBLIC_BRAND_NAME_WORD` | Short abbreviation (e.g. `ZX`) |
|
||||
|
||||
> Do **not** set `NEXT_PUBLIC_DASHBOARD_API_KEY`. The browser uses `/api/proxy`, which adds the secret server-side.
|
||||
|
||||
---
|
||||
|
||||
## ✦ Deployment (Vercel)
|
||||
|
||||
**Step 1 — Connect your repo**
|
||||
|
||||
Go to [vercel.com](https://vercel.com) → **Add New Project** → connect your GitHub repo → set root directory to `dashboard/`
|
||||
|
||||
Vercel auto-detects Next.js — no build settings needed.
|
||||
|
||||
**Step 2 — Add environment variables**
|
||||
|
||||
In **Settings → Environment Variables**, add all keys from the table above.
|
||||
|
||||
| Variable | Production Value |
|
||||
|---|---|
|
||||
| `NEXT_PUBLIC_API_URL` | `https://api.yourdomain.com/api/v1` |
|
||||
| `NEXTAUTH_URL` | `https://your-app.vercel.app` |
|
||||
| `NEXTAUTH_SECRET` | [generate one](https://generate-secret.vercel.app/32) |
|
||||
| `DISCORD_CLIENT_ID` | from [Discord Developer Portal](https://discord.com/developers/applications) |
|
||||
|
||||
**Step 3 — Add redirect URI in Discord**
|
||||
|
||||
In your Discord app → **OAuth2 → Redirects** → add:
|
||||
## How API auth works
|
||||
|
||||
```
|
||||
https://your-app.vercel.app/api/auth/callback/discord
|
||||
Browser → /api/proxy/guilds/... → Next.js (session check)
|
||||
→ Bot API with:
|
||||
Authorization: Bearer DASHBOARD_API_KEY
|
||||
X-Discord-Access-Token: <oauth token>
|
||||
X-Discord-User-Id: <user id>
|
||||
→ Bot verifies Discord Manage Server permission per guild
|
||||
```
|
||||
|
||||
**Step 4 — Deploy**
|
||||
|
||||
Hit **Deploy**. Vercel builds and publishes automatically. ✓
|
||||
SSR (server components) call the bot API directly with the same headers from the active session.
|
||||
|
||||
---
|
||||
|
||||
## ✦ Connecting to the Bot API
|
||||
## Deployment (Vercel)
|
||||
|
||||
The dashboard reads the API URL from `NEXT_PUBLIC_API_URL`.
|
||||
1. Connect repo → set root directory to `dashboard/`
|
||||
2. Add all environment variables from the table above
|
||||
3. Set `NEXTAUTH_URL` to your Vercel domain
|
||||
4. Add OAuth redirect: `https://your-app.vercel.app/api/auth/callback/discord`
|
||||
5. Deploy
|
||||
|
||||
| Environment | Value |
|
||||
|---|---|
|
||||
| Local dev | `http://localhost:8000/api/v1` |
|
||||
| Production | `https://api.yourdomain.com/api/v1` (Cloudflare Tunnel URL) |
|
||||
For production with Cloudflare Tunnel, set:
|
||||
|
||||
The bot prints the confirmed URL on every startup:
|
||||
```env
|
||||
DASHBOARD_API_URL=https://api.yourdomain.com/api/v1
|
||||
```
|
||||
◈ Tunnel: API is live at https://api.yourdomain.com
|
||||
↳ NEXT_PUBLIC_API_URL = https://api.yourdomain.com/api/v1
|
||||
```
|
||||
|
||||
This URL is permanent — it never changes between restarts as long as the Cloudflare Tunnel token stays the same.
|
||||
|
||||
---
|
||||
|
||||
## ✦ Troubleshooting
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Fix |
|
||||
|---|---|
|
||||
| Auth error on login | Check Discord OAuth client ID/secret and redirect URI in Developer Portal |
|
||||
| Dashboard can't load data | Confirm bot is running with `API_ENABLED=true` and `NEXT_PUBLIC_API_URL` is correct |
|
||||
| CORS error in browser | Add your Vercel URL to `CORS_ORIGINS` in the bot's `.env` |
|
||||
| `NEXTAUTH_SECRET` error | Make sure `NEXTAUTH_SECRET` is set and non-empty |
|
||||
| API key rejected (401) | `NEXT_PUBLIC_DASHBOARD_API_KEY` must exactly match `DASHBOARD_API_KEY` in the bot |
|
||||
| Tunnel URL changed | Cloudflare named tunnels always produce the same URL — check `CF_TUNNEL_TOKEN` is valid |
|
||||
| Dashboard can't load data | Bot running with `API_ENABLED=true`, `DASHBOARD_API_URL` correct |
|
||||
| 401 from bot API | `DASHBOARD_API_KEY` must match bot `.env` exactly |
|
||||
| 403 on guild routes | User must have Manage Server or Admin on that Discord server |
|
||||
| Admin panel 403 | Add your Discord ID to `ADMIN_IDS` and bot `DASHBOARD_ADMIN_IDS` |
|
||||
| Auth error on login | Check Discord OAuth client ID/secret and redirect URI |
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## ✦ CodeX Devs
|
||||
|
||||
*Built for protection. Designed for style.*
|
||||
|
||||
<a href="https://discord.gg/codexdev"><img src="https://discord.com/api/guilds/1301573144817045524/widget.png?style=banner2" alt="CodeX Development Discord Server" width="480"/></a>
|
||||
|
||||
<p>
|
||||
<a href="https://discord.gg/codexdev"><img src="https://img.shields.io/badge/Discord-Join_Server-5865F2?style=for-the-badge&logo=discord&logoColor=white"/></a>
|
||||
<a href="https://youtube.com/@CodeXDevs"><img src="https://img.shields.io/badge/YouTube-CodeXDevs-FF0000?style=for-the-badge&logo=youtube&logoColor=white"/></a>
|
||||
<a href="https://github.com/RayExo"><img src="https://img.shields.io/badge/GitHub-RayExo-181717?style=for-the-badge&logo=github&logoColor=white"/></a>
|
||||
<a href="https://nexiohost.in"><img src="https://img.shields.io/badge/⭐%20PREMIUM%20HOSTING-NexioHost-FFD700?style=for-the-badge&labelColor=1a1a2e&color=FFD700&logoColor=FFD700"/></a>
|
||||
</p>
|
||||
|
||||
© 2026 CodeX Devs — MIT License
|
||||
|
||||
</div>
|
||||
See also `SECURITY_FIXES.md` in the project root.
|
||||
|
||||
146
dashboard/app/api/proxy/[...path]/route.ts
Normal file
146
dashboard/app/api/proxy/[...path]/route.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Authenticated server-side proxy to the bot FastAPI backend.
|
||||
* - Requires Discord OAuth session
|
||||
* - Guild routes: user must have Manage Server / Admin on that guild
|
||||
* - Admin routes: user must be in ADMIN_IDS
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { isAdmin } from "@/lib/utils";
|
||||
import { userCanManageGuild } from "@/lib/guild-auth";
|
||||
|
||||
const BOT_API_URL =
|
||||
process.env.DASHBOARD_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
"http://127.0.0.1:8000/api/v1";
|
||||
|
||||
const API_KEY = process.env.DASHBOARD_API_KEY;
|
||||
|
||||
type RouteContext = { params: { path: string[] } };
|
||||
|
||||
async function authorizeProxyRequest(
|
||||
path: string,
|
||||
session: { user?: { id?: string }; accessToken?: string }
|
||||
): Promise<NextResponse | null> {
|
||||
if (!session.user) {
|
||||
return NextResponse.json({ detail: "Unauthorized — sign in required." }, { status: 401 });
|
||||
}
|
||||
|
||||
const accessToken = session.accessToken;
|
||||
if (!accessToken) {
|
||||
return NextResponse.json({ detail: "Missing Discord access token." }, { status: 401 });
|
||||
}
|
||||
|
||||
const normalized = path.replace(/\/$/, "");
|
||||
|
||||
if (normalized.startsWith("admin")) {
|
||||
if (!isAdmin(session.user.id)) {
|
||||
return NextResponse.json({ detail: "Forbidden — admin access required." }, { status: 403 });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const guildMatch = normalized.match(/^guilds\/(\d+)/);
|
||||
if (guildMatch) {
|
||||
const guildId = guildMatch[1];
|
||||
const allowed = await userCanManageGuild(accessToken, guildId);
|
||||
if (!allowed) {
|
||||
return NextResponse.json(
|
||||
{ detail: "Forbidden — you cannot manage this server." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function proxyRequest(request: NextRequest, { params }: RouteContext) {
|
||||
if (!API_KEY) {
|
||||
return NextResponse.json(
|
||||
{ detail: "DASHBOARD_API_KEY is not configured on the dashboard server." },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
const path = params.path.join("/");
|
||||
|
||||
const authError = await authorizeProxyRequest(path, session ?? {});
|
||||
if (authError) return authError;
|
||||
|
||||
const targetUrl = `${BOT_API_URL.replace(/\/$/, "")}/${path}${request.nextUrl.search}`;
|
||||
|
||||
const headers = new Headers();
|
||||
headers.set("Authorization", `Bearer ${API_KEY}`);
|
||||
|
||||
if (session?.accessToken) {
|
||||
headers.set("X-Discord-Access-Token", session.accessToken);
|
||||
}
|
||||
if (session?.user?.id) {
|
||||
headers.set("X-Discord-User-Id", session.user.id);
|
||||
}
|
||||
|
||||
const contentType = request.headers.get("content-type");
|
||||
if (contentType) {
|
||||
headers.set("Content-Type", contentType);
|
||||
}
|
||||
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers,
|
||||
cache: "no-store",
|
||||
};
|
||||
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = await request.text();
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(targetUrl, init);
|
||||
let body = await response.text();
|
||||
|
||||
// Filter guild list to servers the user can manage (bot guild list ∩ user admin guilds)
|
||||
const normalized = path.replace(/\/$/, "");
|
||||
if (
|
||||
request.method === "GET" &&
|
||||
normalized === "guilds" &&
|
||||
response.ok &&
|
||||
session?.accessToken
|
||||
) {
|
||||
try {
|
||||
const botGuilds = JSON.parse(body) as Array<{ id: string }>;
|
||||
const { fetchUserGuilds, canManageGuild } = await import("@/lib/guild-auth");
|
||||
const userGuilds = await fetchUserGuilds(session.accessToken);
|
||||
const manageableIds = new Set(
|
||||
userGuilds.filter(canManageGuild).map((g) => String(g.id))
|
||||
);
|
||||
const filtered = botGuilds.filter((g) => manageableIds.has(String(g.id)));
|
||||
body = JSON.stringify(filtered);
|
||||
} catch {
|
||||
// If filtering fails, return original response rather than breaking the dashboard
|
||||
}
|
||||
}
|
||||
|
||||
return new NextResponse(body, {
|
||||
status: response.status,
|
||||
headers: {
|
||||
"Content-Type": response.headers.get("Content-Type") || "application/json",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`[API Proxy] Failed to reach bot API at ${targetUrl}:`, error);
|
||||
return NextResponse.json(
|
||||
{ detail: "Could not connect to the bot API backend." },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = proxyRequest;
|
||||
export const POST = proxyRequest;
|
||||
export const PATCH = proxyRequest;
|
||||
export const DELETE = proxyRequest;
|
||||
export const PUT = proxyRequest;
|
||||
@@ -32,6 +32,10 @@ import {
|
||||
} from "lucide-react";
|
||||
import { api } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { userCanManageGuild } from "@/lib/guild-auth";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export const revalidate = 0; // Never cache any guild dashboard page
|
||||
|
||||
@@ -51,6 +55,27 @@ export default async function GuildLayout({
|
||||
let guild;
|
||||
let error = null;
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.accessToken) {
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
const hasGuildAccess = await userCanManageGuild(session.accessToken, guildId);
|
||||
if (!hasGuildAccess) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-[400px] border-2 border-dashed border-red-500/20 rounded-3xl bg-red-500/5 p-12 text-center">
|
||||
<ShieldAlert className="h-16 w-16 text-red-500 mb-6 opacity-50" />
|
||||
<h2 className="text-2xl font-bold text-white">Access Denied</h2>
|
||||
<p className="text-slate-400 mt-2 max-w-md">
|
||||
You do not have permission to manage this server.
|
||||
</p>
|
||||
<Link href="/dashboard/guilds" className="mt-8">
|
||||
<Button variant="outline">Back to Servers</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
guild = await api.getGuildDetails(guildId);
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -38,8 +38,14 @@ import {
|
||||
AdminConfigUpdate
|
||||
} from "@/types/api";
|
||||
|
||||
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000/api/v1";
|
||||
const API_KEY = process.env.NEXT_PUBLIC_DASHBOARD_API_KEY;
|
||||
const isServer = typeof window === "undefined";
|
||||
|
||||
/** Server: direct bot API with secret key. Browser: same-origin proxy route. */
|
||||
const BASE_URL = isServer
|
||||
? (process.env.DASHBOARD_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
"http://127.0.0.1:8000/api/v1")
|
||||
: "/api/proxy";
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(public status: number, message: string) {
|
||||
@@ -55,8 +61,20 @@ async function request<T>(
|
||||
const url = `${BASE_URL}${endpoint}`;
|
||||
|
||||
const headers = new Headers(options.headers);
|
||||
if (API_KEY) {
|
||||
headers.set("Authorization", `Bearer ${API_KEY}`);
|
||||
if (isServer) {
|
||||
const apiKey = process.env.DASHBOARD_API_KEY;
|
||||
if (apiKey) {
|
||||
headers.set("Authorization", `Bearer ${apiKey}`);
|
||||
}
|
||||
const { getServerSession } = await import("next-auth/next");
|
||||
const { authOptions } = await import("@/lib/auth");
|
||||
const session = await getServerSession(authOptions);
|
||||
if (session?.accessToken) {
|
||||
headers.set("X-Discord-Access-Token", session.accessToken);
|
||||
}
|
||||
if (session?.user?.id) {
|
||||
headers.set("X-Discord-User-Id", session.user.id);
|
||||
}
|
||||
}
|
||||
headers.set("Content-Type", "application/json");
|
||||
try {
|
||||
|
||||
45
dashboard/lib/guild-auth.ts
Normal file
45
dashboard/lib/guild-auth.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Discord guild permission helpers for dashboard access control.
|
||||
*/
|
||||
|
||||
export interface DiscordGuild {
|
||||
id: string;
|
||||
permissions: string;
|
||||
owner?: boolean;
|
||||
}
|
||||
|
||||
const MANAGE_GUILD = BigInt(0x20);
|
||||
const ADMINISTRATOR = BigInt(0x8);
|
||||
|
||||
export function canManageGuild(guild: DiscordGuild): boolean {
|
||||
if (guild.owner) return true;
|
||||
try {
|
||||
const perms = BigInt(guild.permissions);
|
||||
return (
|
||||
(perms & ADMINISTRATOR) === ADMINISTRATOR ||
|
||||
(perms & MANAGE_GUILD) === MANAGE_GUILD
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchUserGuilds(
|
||||
accessToken: string
|
||||
): Promise<DiscordGuild[]> {
|
||||
const res = await fetch("https://discord.com/api/users/@me/guilds", {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function userCanManageGuild(
|
||||
accessToken: string,
|
||||
guildId: string
|
||||
): Promise<boolean> {
|
||||
const guilds = await fetchUserGuilds(accessToken);
|
||||
const guild = guilds.find((g) => String(g.id) === String(guildId));
|
||||
return guild ? canManageGuild(guild) : false;
|
||||
}
|
||||
@@ -23,6 +23,11 @@ export function cn(...inputs: ClassValue[]) {
|
||||
|
||||
export function isAdmin(userId?: string | null) {
|
||||
if (!userId) return false;
|
||||
const adminIds = (process.env.NEXT_PUBLIC_ADMIN_IDS || "").split(",");
|
||||
const adminIds = [
|
||||
...(process.env.ADMIN_IDS || "").split(","),
|
||||
...(process.env.NEXT_PUBLIC_ADMIN_IDS || "").split(","),
|
||||
]
|
||||
.map((id) => id.trim())
|
||||
.filter(Boolean);
|
||||
return adminIds.includes(userId);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user