Add admin Articles (CRUD) + Bans resources

- Articles: list / new / edit / delete (websiteArticles), unique-slug
  generation via slugify() (pure, unit-tested); staff-gated server actions.
- Bans: list active bans (ban_expire > now), create ban (writes the bans row +
  RCON disconnect) with type/duration/reason, lift ban; staff-gated actions.
- Admin nav extended (Articles, Bans).

Verified: tsc exit 0, vitest 48/48, next build exit 0 (7 /admin routes).
This commit is contained in:
Simo committed 2026-06-28 12:52:38 +02:00
1 parent 9f81096f05
commit 5861d9f1f5
9 files changed
+310 -1

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { slugify } from "@/lib/format";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
async function uniqueSlug(title: string): Promise<string> {
const base = slugify(title);
let slug = base;
let n = 2;
while (await prisma.websiteArticles.findUnique({ where: { slug } })) {
slug = `${base}-${n++}`;
}
return slug;
}
export async function createArticle(formData: FormData): Promise<void> {
const staff = await requireStaff();
const title = String(formData.get("title") ?? "").trim();
const shortStory = String(formData.get("shortStory") ?? "").trim();
const fullStory = String(formData.get("fullStory") ?? "").trim();
const image = String(formData.get("image") ?? "").trim();
if (!title) return;
const now = new Date();
await prisma.websiteArticles.create({
data: {
slug: await uniqueSlug(title),
title: title.slice(0, 255),
shortStory: shortStory.slice(0, 255),
fullStory,
image: image.slice(0, 255),
userId: String(staff.id),
createdAt: now,
updatedAt: now,
},
});
redirect("/admin/articles");
}
export async function updateArticle(formData: FormData): Promise<void> {
await requireStaff();
const id = BigInt(String(formData.get("id")));
await prisma.websiteArticles.update({
where: { id },
data: {
title: String(formData.get("title") ?? "").trim().slice(0, 255),
shortStory: String(formData.get("shortStory") ?? "").trim().slice(0, 255),
fullStory: String(formData.get("fullStory") ?? "").trim(),
image: String(formData.get("image") ?? "").trim().slice(0, 255),
updatedAt: new Date(),
},
});
revalidatePath(`/admin/articles/${id}`);
redirect("/admin/articles");
}
export async function deleteArticle(formData: FormData): Promise<void> {
await requireStaff();
await prisma.websiteArticles.delete({ where: { id: BigInt(String(formData.get("id"))) } });
redirect("/admin/articles");
}
+51
View File
@@ -0,0 +1,51 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
type BanType = "account" | "ip" | "machine" | "super";
const BAN_TYPES: ReadonlySet<string> = new Set(["account", "ip", "machine", "super"]);
const PERMANENT_SECONDS = 100 * 365 * 24 * 3600;
export async function createBan(formData: FormData): Promise<void> {
const staff = await requireStaff();
const userId = Number(formData.get("userId"));
const reason = String(formData.get("reason") ?? "").trim().slice(0, 200) || "Banned";
const hours = Number(formData.get("hours"));
const type = String(formData.get("type"));
if (!(userId > 0) || !BAN_TYPES.has(type)) return;
const now = Math.floor(Date.now() / 1000);
const banExpire = hours > 0 ? now + Math.floor(hours) * 3600 : now + PERMANENT_SECONDS;
const user = await prisma.user.findUnique({
where: { id: userId },
select: { username: true },
});
await prisma.ban.create({
data: {
userId,
ip: "",
machineId: "",
userStaffId: staff.id,
timestamp: now,
banExpire,
banReason: reason,
type: type as BanType,
cfhTopic: -1,
},
});
if (user) await rcon.disconnectUser(userId, user.username);
revalidatePath("/admin/bans");
}
export async function liftBan(formData: FormData): Promise<void> {
await requireStaff();
const id = Number(formData.get("id"));
if (id > 0) await prisma.ban.delete({ where: { id } });
revalidatePath("/admin/bans");
}
+42
View File
@@ -0,0 +1,42 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { deleteArticle, updateArticle } from "@/actions/admin-articles";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function EditArticle({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
let article: Awaited<ReturnType<typeof prisma.websiteArticles.findUnique>> = null;
try {
article = await prisma.websiteArticles.findUnique({ where: { id: BigInt(id) } });
} catch {
notFound();
}
if (!article) notFound();
return (
<main>
<p className="muted">
<Link href="/admin/articles">← Articles</Link>
</p>
<h1>Edit article</h1>
<form action={updateArticle} className="card" style={{ display: "grid", gap: "0.6rem" }}>
<input type="hidden" name="id" value={String(article.id)} />
<input name="title" defaultValue={article.title} required />
<input name="image" defaultValue={article.image} placeholder="Image URL" />
<textarea name="shortStory" defaultValue={article.shortStory} rows={2} />
<textarea name="fullStory" defaultValue={article.fullStory} rows={10} />
<button type="submit">Save</button>
</form>
<form action={deleteArticle} style={{ marginTop: "1rem" }}>
<input type="hidden" name="id" value={String(article.id)} />
<button type="submit">Delete article</button>
</form>
</main>
);
}
+20
View File
@@ -0,0 +1,20 @@
import Link from "next/link";
import { createArticle } from "@/actions/admin-articles";
export default function NewArticle() {
return (
<main>
<p className="muted">
<Link href="/admin/articles">← Articles</Link>
</p>
<h1>New article</h1>
<form action={createArticle} className="card" style={{ display: "grid", gap: "0.6rem" }}>
<input name="title" placeholder="Title" required />
<input name="image" placeholder="Image URL" />
<textarea name="shortStory" placeholder="Short story (summary)" rows={2} />
<textarea name="fullStory" placeholder="Full story" rows={10} />
<button type="submit">Create</button>
</form>
</main>
);
}
+41
View File
@@ -0,0 +1,41 @@
import Link from "next/link";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function AdminArticles() {
const articles = await prisma.websiteArticles.findMany({
orderBy: { createdAt: "desc" },
select: { id: true, title: true, slug: true, createdAt: true },
take: 50,
});
return (
<main>
<div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
<h1 style={{ flex: 1 }}>Articles</h1>
<Link href="/admin/articles/new">+ New article</Link>
</div>
<table style={{ width: "100%", borderCollapse: "collapse" }}>
<thead>
<tr style={{ textAlign: "left", color: "var(--muted)" }}>
<th>Title</th>
<th>Slug</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{articles.map((a) => (
<tr key={String(a.id)} style={{ borderTop: "1px solid var(--border)" }}>
<td>
<Link href={`/admin/articles/${a.id}`}>{a.title}</Link>
</td>
<td className="muted">{a.slug}</td>
<td className="muted">{a.createdAt ? a.createdAt.toISOString().slice(0, 10) : ""}</td>
</tr>
))}
</tbody>
</table>
</main>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { createBan, liftBan } from "@/actions/admin-bans";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
export default async function AdminBans() {
const now = Math.floor(Date.now() / 1000);
const bans = await prisma.ban.findMany({
where: { banExpire: { gt: now } },
orderBy: { timestamp: "desc" },
take: 100,
});
return (
<main>
<h1>Bans</h1>
<form action={createBan} className="card" style={{ marginBottom: "1.5rem" }}>
<h3 style={{ marginTop: 0 }}>New ban</h3>
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
<input name="userId" type="number" min={1} placeholder="User ID" required />
<select name="type">
<option value="account">account</option>
<option value="ip">ip</option>
<option value="machine">machine</option>
<option value="super">super</option>
</select>
<input name="hours" type="number" min={0} placeholder="Hours (0 = perm)" />
<input name="reason" placeholder="Reason" style={{ flex: 1, minWidth: 160 }} />
<button type="submit">Ban</button>
</div>
</form>
<table style={{ width: "100%", borderCollapse: "collapse" }}>
<thead>
<tr style={{ textAlign: "left", color: "var(--muted)" }}>
<th>User ID</th>
<th>Type</th>
<th>Reason</th>
<th>Expires</th>
<th />
</tr>
</thead>
<tbody>
{bans.map((b) => (
<tr key={b.id} style={{ borderTop: "1px solid var(--border)" }}>
<td>{b.userId}</td>
<td>{b.type}</td>
<td>{b.banReason}</td>
<td className="muted">{new Date(b.banExpire * 1000).toISOString().slice(0, 16).replace("T", " ")}</td>
<td>
<form action={liftBan}>
<input type="hidden" name="id" value={b.id} />
<button type="submit">Lift</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
{bans.length === 0 ? <p className="muted">No active bans.</p> : null}
</main>
);
}
+2
View File
@@ -16,6 +16,8 @@ export default async function AdminLayout({ children }: { children: ReactNode })
<nav style={{ display: "grid", gap: "0.45rem" }}>
<Link href="/admin">Dashboard</Link>
<Link href="/admin/users">Users</Link>
<Link href="/admin/articles">Articles</Link>
<Link href="/admin/bans">Bans</Link>
</nav>
</aside>
<section>{children}</section>
+13 -1
View File
@@ -1,5 +1,17 @@
import { describe, expect, it } from "vitest";
import { avatarImageUrl, excerpt } from "./format";
import { avatarImageUrl, excerpt, slugify } from "./format";
describe("slugify", () => {
it("lowercases and hyphenates", () => {
expect(slugify("Hello World!")).toBe("hello-world");
});
it("strips accents via NFKD", () => {
expect(slugify("Café del Mar")).toBe("cafe-del-mar");
});
it("falls back to 'article' for empty input", () => {
expect(slugify(" *** ")).toBe("article");
});
});
describe("avatarImageUrl", () => {
const base = "https://www.habbo.com/habbo-imaging/avatarimage";
+13
View File
@@ -12,6 +12,19 @@ export function avatarImageUrl(
return `${base}${sep}${params.toString()}`;
}
/** URL-safe slug from a title (lowercase, ascii, hyphenated). */
export function slugify(input: string): string {
// NFKD splits accented letters into base + combining mark; the combining
// marks (and any other non-alphanumerics) are then collapsed to hyphens.
const slug = input
.toLowerCase()
.normalize("NFKD")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
return slug || "article";
}
/** Trim text to `max` chars on a word boundary, adding an ellipsis. */
export function excerpt(text: string, max = 160): string {
if (text.length <= max) return text;