feat(admin): add hidden admin panel, ban system, ads, and legal pages

- Admin panel at /p/[ADMIN_SECRET]/* — middleware returns 404 for wrong/missing secret
- tRPC adminRouter: getStats, listPosts, deletePost, listComments, deleteComment,
  listUsers, banUser/unbanUser, listAds, createAd/updateAd/deleteAd, getActiveAds,
  listModerators, grantRole/revokeRole, getModerationLog, getActiveBan
- Prisma schema: AdminRole, UserBan, Advertisement, ModerationLog models added
- Ban enforcement: (app)/layout.tsx checks active ban on every request → /banned
- Feed ad injection: active ads shown every 7th post in FeedList (AdCard component)
- Clerk middleware.ts: protects all routes; /p/[secret] validated before auth check
- Impressum + Datenschutz pages: contact data base64-obfuscated, decoded client-side only
- shadcn Switch component added
- ADMIN_SECRET + ADMIN_OWNER_ID documented in .env.example
This commit is contained in:
admin committed 2026-06-21 15:21:07 +02:00
1 parent e407064866
commit b5f02fe7a4
18 files changed
+1815 -6

No files matched your search

+2
View File
@@ -17,6 +17,7 @@ import { notificationsRouter } from "@/trpc/routers/notifications";
import { videosRouter } from "@/trpc/routers/videos";
import { conversationsRouter, messagesRouter } from "@/trpc/routers/messages";
import { healthRouter } from "@/trpc/routers/health";
import { adminRouter } from "@/trpc/routers/admin";
export const appRouter = router({
pets: petsRouter,
@@ -38,6 +39,7 @@ export const appRouter = router({
conversations: conversationsRouter,
messages: messagesRouter,
health: healthRouter,
admin: adminRouter,
});
// Export the type for use in the client
+348
View File
@@ -0,0 +1,348 @@
import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { AdminRoleType, type PrismaClient } from "@prisma/client";
import { router, protectedProcedure } from "@/trpc/init";
async function assertAdmin(
prisma: PrismaClient,
userId: string,
requireSuperAdmin = false
) {
const isSuperOwner = process.env.ADMIN_OWNER_ID === userId;
if (isSuperOwner && !requireSuperAdmin) return;
if (isSuperOwner) return;
const role = await prisma.adminRole.findUnique({ where: { ownerId: userId } });
if (!role) throw new TRPCError({ code: "FORBIDDEN" });
if (requireSuperAdmin && role.role !== AdminRoleType.SUPER_ADMIN) {
throw new TRPCError({ code: "FORBIDDEN" });
}
}
export const adminRouter = router({
// ─── Ban status check (no admin role required) ───────────────────────────────
getActiveBan: protectedProcedure
.input(z.object({ ownerId: z.string().min(1) }))
.query(async ({ ctx, input }) => {
// Only the owner themselves or an admin should query ban status
if (input.ownerId !== ctx.userId) {
const isAdmin =
process.env.ADMIN_OWNER_ID === ctx.userId ||
(await ctx.prisma.adminRole.findUnique({ where: { ownerId: ctx.userId } })) !== null;
if (!isAdmin) throw new TRPCError({ code: "FORBIDDEN" });
}
const ban = await ctx.prisma.userBan.findUnique({ where: { ownerId: input.ownerId } });
if (!ban) return null;
// Check if a temporary ban has expired
if (ban.expiresAt && ban.expiresAt < new Date()) {
await ctx.prisma.userBan.delete({ where: { id: ban.id } }).catch(() => {});
return null;
}
return ban;
}),
// ─── Dashboard ───────────────────────────────────────────────────────────────
getStats: protectedProcedure.query(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId);
const [owners, pets, posts, bans, ads, reports] = await Promise.all([
ctx.prisma.owner.count(),
ctx.prisma.pet.count(),
ctx.prisma.post.count(),
ctx.prisma.userBan.count(),
ctx.prisma.advertisement.count({ where: { isActive: true } }),
ctx.prisma.report.count(),
]);
return { owners, pets, posts, bans, activeAds: ads, reports };
}),
// ─── Post moderation ─────────────────────────────────────────────────────────
listPosts: protectedProcedure
.input(
z.object({
cursor: z.string().nullish(),
limit: z.number().min(1).max(50).default(20),
search: z.string().optional(),
})
)
.query(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
const posts = await ctx.prisma.post.findMany({
where: input.search
? { caption: { contains: input.search, mode: "insensitive" } }
: undefined,
include: {
pet: { select: { id: true, name: true, avatarKey: true, ownerId: true } },
images: { orderBy: { position: "asc" }, take: 1 },
_count: { select: { reactions: true, comments: true, reports: true } },
},
orderBy: { createdAt: "desc" },
take: input.limit + 1,
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
});
const hasNext = posts.length > input.limit;
const items = hasNext ? posts.slice(0, input.limit) : posts;
return { posts: items, nextCursor: hasNext ? items[items.length - 1]!.id : null };
}),
deletePost: protectedProcedure
.input(z.object({ postId: z.string().min(1), reason: z.string().max(500).optional() }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
await ctx.prisma.post.delete({ where: { id: input.postId } });
await ctx.prisma.moderationLog.create({
data: {
action: "DELETE_POST",
targetType: "POST",
targetId: input.postId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
},
});
return { success: true };
}),
listComments: protectedProcedure
.input(z.object({ postId: z.string().min(1) }))
.query(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
return ctx.prisma.comment.findMany({
where: { postId: input.postId },
include: { pet: { select: { id: true, name: true, avatarKey: true } } },
orderBy: { createdAt: "asc" },
});
}),
deleteComment: protectedProcedure
.input(z.object({ commentId: z.string().min(1), reason: z.string().max(500).optional() }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
await ctx.prisma.comment.delete({ where: { id: input.commentId } });
await ctx.prisma.moderationLog.create({
data: {
action: "DELETE_COMMENT",
targetType: "COMMENT",
targetId: input.commentId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
},
});
return { success: true };
}),
// ─── Users / bans ────────────────────────────────────────────────────────────
listUsers: protectedProcedure
.input(z.object({ cursor: z.string().nullish(), limit: z.number().min(1).max(50).default(20) }))
.query(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
const owners = await ctx.prisma.owner.findMany({
include: {
pets: { select: { id: true, name: true, avatarKey: true }, take: 3 },
ban: true,
adminRole: true,
_count: { select: { pets: true } },
},
orderBy: { createdAt: "desc" },
take: input.limit + 1,
...(input.cursor ? { skip: 1, cursor: { id: input.cursor } } : {}),
});
const hasNext = owners.length > input.limit;
const items = hasNext ? owners.slice(0, input.limit) : owners;
return { users: items, nextCursor: hasNext ? items[items.length - 1]!.id : null };
}),
banUser: protectedProcedure
.input(
z.object({
ownerId: z.string().min(1),
reason: z.string().max(500).optional(),
expiresAt: z.string().datetime().optional(),
})
)
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
if (input.ownerId === ctx.userId)
throw new TRPCError({ code: "BAD_REQUEST", message: "Cannot ban yourself." });
await ctx.prisma.userBan.upsert({
where: { ownerId: input.ownerId },
create: {
ownerId: input.ownerId,
reason: input.reason ?? null,
bannedBy: ctx.userId,
expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
},
update: {
reason: input.reason ?? null,
bannedBy: ctx.userId,
bannedAt: new Date(),
expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
},
});
await ctx.prisma.moderationLog.create({
data: {
action: "BAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
},
});
return { success: true };
}),
unbanUser: protectedProcedure
.input(z.object({ ownerId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
await ctx.prisma.userBan.delete({ where: { ownerId: input.ownerId } });
await ctx.prisma.moderationLog.create({
data: {
action: "UNBAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: null,
moderatorId: ctx.userId,
},
});
return { success: true };
}),
// ─── Reports ─────────────────────────────────────────────────────────────────
listReports: protectedProcedure.query(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId);
return ctx.prisma.report.findMany({
include: {
reporter: { select: { id: true, name: true } },
post: { select: { id: true, caption: true, petId: true } },
},
orderBy: { createdAt: "desc" },
take: 50,
});
}),
// ─── Advertisements ──────────────────────────────────────────────────────────
listAds: protectedProcedure.query(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId);
return ctx.prisma.advertisement.findMany({ orderBy: { createdAt: "desc" } });
}),
createAd: protectedProcedure
.input(
z.object({
title: z.string().min(1).max(100),
caption: z.string().max(500).optional(),
imageKey: z.string().optional(),
targetUrl: z.string().url().or(z.literal("")).optional(),
isActive: z.boolean().default(true),
species: z.array(z.string()).default([]),
startDate: z.string().datetime().optional(),
endDate: z.string().datetime().optional(),
})
)
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
return ctx.prisma.advertisement.create({
data: {
title: input.title,
caption: input.caption ?? null,
imageKey: input.imageKey ?? null,
targetUrl: input.targetUrl || null,
isActive: input.isActive,
species: input.species,
startDate: input.startDate ? new Date(input.startDate) : null,
endDate: input.endDate ? new Date(input.endDate) : null,
createdBy: ctx.userId,
},
});
}),
updateAd: protectedProcedure
.input(
z.object({
id: z.string().min(1),
title: z.string().min(1).max(100).optional(),
caption: z.string().max(500).nullable().optional(),
imageKey: z.string().nullable().optional(),
targetUrl: z.string().url().or(z.literal("")).nullable().optional(),
isActive: z.boolean().optional(),
species: z.array(z.string()).optional(),
startDate: z.string().datetime().nullable().optional(),
endDate: z.string().datetime().nullable().optional(),
})
)
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
const { id, targetUrl, startDate, endDate, ...rest } = input;
return ctx.prisma.advertisement.update({
where: { id },
data: {
...rest,
targetUrl: targetUrl === "" ? null : targetUrl,
startDate: startDate ? new Date(startDate) : startDate === null ? null : undefined,
endDate: endDate ? new Date(endDate) : endDate === null ? null : undefined,
},
});
}),
deleteAd: protectedProcedure
.input(z.object({ id: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
await ctx.prisma.advertisement.delete({ where: { id: input.id } });
return { success: true };
}),
getActiveAds: protectedProcedure.query(async ({ ctx }) => {
const now = new Date();
return ctx.prisma.advertisement.findMany({
where: {
isActive: true,
OR: [{ startDate: null }, { startDate: { lte: now } }],
AND: [{ OR: [{ endDate: null }, { endDate: { gte: now } }] }],
},
orderBy: { createdAt: "desc" },
});
}),
// ─── Moderator management (super-admin only) ─────────────────────────────────
listModerators: protectedProcedure.query(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId);
return ctx.prisma.adminRole.findMany({
include: {
owner: {
include: { pets: { select: { name: true, avatarKey: true }, take: 1 } },
},
},
orderBy: { grantedAt: "desc" },
});
}),
grantRole: protectedProcedure
.input(z.object({ ownerId: z.string().min(1), role: z.nativeEnum(AdminRoleType) }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId, true);
return ctx.prisma.adminRole.upsert({
where: { ownerId: input.ownerId },
create: { ownerId: input.ownerId, role: input.role, grantedBy: ctx.userId },
update: { role: input.role, grantedBy: ctx.userId, grantedAt: new Date() },
});
}),
revokeRole: protectedProcedure
.input(z.object({ ownerId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId, true);
await ctx.prisma.adminRole.delete({ where: { ownerId: input.ownerId } });
return { success: true };
}),
getModerationLog: protectedProcedure
.input(z.object({ limit: z.number().min(1).max(100).default(50) }))
.query(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId);
return ctx.prisma.moderationLog.findMany({
orderBy: { createdAt: "desc" },
take: input.limit,
});
}),
});