Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Ban/unban users from the control panel (#2628)

Luke Vella58e3131e70c8
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 66775741d..daede3183 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -66,6 +66,12 @@
"autoTimeZone": "Automatic Time Zone Conversion",
"autoTimeZoneHelp": "Enable this setting to automatically adjust event times to each participant's local time zone.",
"back": "Back",
+ "banned": "Banned",
+ "banUser": "Ban user",
+ "banUserDesc": "Are you sure you want to ban <b>{email}</b>? They will be signed out and won't be able to log in.",
+ "banUserReason": "Reason (optional)",
+ "banUserReasonTooLong": "Reason must be 500 characters or fewer",
+ "banUserTitle": "Ban User",
"basicPolls": "Basic Polls",
"basicPollsDescription": "Create simple scheduling polls",
"becomeATranslator": "Help translate",
@@ -457,7 +463,6 @@
"outlook": "Outlook",
"owner": "Owner",
"ownerPermissionsRequired": "Only space owners can access billing settings.",
- "pageMovedDescription": "Redirecting to <a>{newUrl}</a>",
"paginationItems": "Showing {startItem}–{endItem} of {totalItems}",
"paginationNext": "Next",
"paginationPage": "Page {currentPage, number} of {totalPages, number}",
@@ -665,6 +670,7 @@
"today": "Today",
"tooManyVerificationAttempts": "Too many incorrect attempts. Request a new code to continue.",
"totalSeats": "Total Seats",
+ "unbanUser": "Unban user",
"unconfirmedEventsEmptyStateDescription": "Unconfirmed events will show up here.",
"unconfirmedEventsEmptyStateTitle": "No Unconfirmed Events",
"unexpectedError": "Unexpected Error",
diff --git a/apps/web/src/app/[locale]/control-panel/users/dialogs/ban-user-dialog.tsx b/apps/web/src/app/[locale]/control-panel/users/dialogs/ban-user-dialog.tsx
new file mode 100644
index 000000000..fa187c3f0
--- /dev/null
+++ b/apps/web/src/app/[locale]/control-panel/users/dialogs/ban-user-dialog.tsx
@@ -0,0 +1,129 @@
+"use client";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Button } from "@rallly/ui/button";
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@rallly/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@rallly/ui/form";
+import { Textarea } from "@rallly/ui/textarea";
+import { useForm } from "react-hook-form";
+import * as z from "zod";
+import { banUserAction } from "@/features/user/actions";
+import { Trans, useTranslation } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
+
+const useSchema = () => {
+ const { t } = useTranslation();
+ return z.object({
+ reason: z
+ .string()
+ .trim()
+ .max(500, {
+ error: t("banUserReasonTooLong", {
+ defaultValue: "Reason must be 500 characters or fewer",
+ }),
+ }),
+ });
+};
+
+export function BanUserDialog({
+ userId,
+ email,
+ open,
+ onOpenChange,
+}: {
+ userId: string;
+ email: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const schema = useSchema();
+ const form = useForm({
+ resolver: zodResolver(schema),
+ defaultValues: {
+ reason: "",
+ },
+ });
+
+ const banUser = useSafeAction(banUserAction, {
+ onSuccess: () => {
+ onOpenChange(false);
+ },
+ });
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="banUserTitle" defaults="Ban User" />
+ </DialogTitle>
+ <DialogDescription>
+ <Trans
+ i18nKey="banUserDesc"
+ defaults="Are you sure you want to ban <b>{email}</b>? They will be signed out and won't be able to log in."
+ values={{ email }}
+ components={{
+ b: <b className="whitespace-nowrap font-normal" />,
+ }}
+ />
+ </DialogDescription>
+ </DialogHeader>
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(async (data) => {
+ await banUser.executeAsync({
+ userId,
+ reason: data.reason || undefined,
+ });
+ })}
+ >
+ <FormField
+ control={form.control}
+ name="reason"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans
+ i18nKey="banUserReason"
+ defaults="Reason (optional)"
+ />
+ </FormLabel>
+ <FormControl>
+ <Textarea {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <DialogFooter className="mt-6">
+ <DialogClose render={<Button />}>
+ <Trans i18nKey="cancel" defaults="Cancel" />
+ </DialogClose>
+ <Button
+ variant="destructive"
+ loading={banUser.isExecuting}
+ type="submit"
+ >
+ <Trans i18nKey="banUser" defaults="Ban user" />
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/app/[locale]/control-panel/users/page.tsx b/apps/web/src/app/[locale]/control-panel/users/page.tsx
index 85ad8756a..3b9c322f2 100644
--- a/apps/web/src/app/[locale]/control-panel/users/page.tsx
+++ b/apps/web/src/app/[locale]/control-panel/users/page.tsx
@@ -72,6 +72,7 @@ async function loadData({
email: true,
image: true,
role: true,
+ banned: true,
},
take: pageSize,
skip: (page - 1) * pageSize,
@@ -93,6 +94,7 @@ async function loadData({
...u,
image: u.image ?? undefined,
canChangeRole: ability.can("update", subject("User", u), "role"),
+ canBan: ability.can("update", subject("User", u), "banned"),
canDelete: ability.can("delete", subject("User", u)),
})),
totalUsers,
@@ -149,7 +151,9 @@ export default async function AdminPage(props: {
userId={user.id}
image={user.image}
role={user.role}
+ banned={user.banned}
canChangeRole={user.canChangeRole}
+ canBan={user.canBan}
canDelete={user.canDelete}
/>
))}
diff --git a/apps/web/src/app/[locale]/control-panel/users/user-row.tsx b/apps/web/src/app/[locale]/control-panel/users/user-row.tsx
index 608be50ae..78efb4034 100644
--- a/apps/web/src/app/[locale]/control-panel/users/user-row.tsx
+++ b/apps/web/src/app/[locale]/control-panel/users/user-row.tsx
@@ -1,5 +1,6 @@
"use client";
import { cn } from "@rallly/ui";
+import { Badge } from "@rallly/ui/badge";
import { Button } from "@rallly/ui/button";
import { useDialog } from "@rallly/ui/dialog";
import {
@@ -15,14 +16,21 @@ import {
DropdownMenuTrigger,
} from "@rallly/ui/dropdown-menu";
import { Icon } from "@rallly/ui/icon";
-import { MoreHorizontal, TrashIcon, UserPenIcon } from "lucide-react";
+import {
+ BanIcon,
+ MoreHorizontal,
+ TrashIcon,
+ UserCheckIcon,
+ UserPenIcon,
+} from "lucide-react";
import { useTransition } from "react";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { StackedListItem } from "@/components/stacked-list";
-import { changeRoleAction } from "@/features/user/actions";
+import { changeRoleAction, unbanUserAction } from "@/features/user/actions";
import { userRoleSchema } from "@/features/user/schema";
import { Trans, useTranslation } from "@/i18n/client";
import { useSafeAction } from "@/lib/safe-action/client";
+import { BanUserDialog } from "./dialogs/ban-user-dialog";
import { DeleteUserDialog } from "./dialogs/delete-user-dialog";
export function UserRow({
@@ -31,7 +39,9 @@ export function UserRow({
userId,
image,
role,
+ banned,
canChangeRole,
+ canBan,
canDelete,
}: {
name: string;
@@ -39,14 +49,18 @@ export function UserRow({
userId: string;
image?: string;
role: "admin" | "user";
+ banned: boolean;
canChangeRole: boolean;
+ canBan: boolean;
canDelete: boolean;
}) {
const { t } = useTranslation();
const changeRole = useSafeAction(changeRoleAction);
+ const unbanUser = useSafeAction(unbanUserAction);
const [isPending, startTransition] = useTransition();
const deleteDialog = useDialog();
+ const banDialog = useDialog();
return (
<>
@@ -63,6 +77,11 @@ export function UserRow({
<div className="truncate text-muted-foreground">{email}</div>
</div>
<div className="flex items-center gap-4">
+ {banned ? (
+ <Badge variant="destructive">
+ <Trans i18nKey="banned" defaults="Banned" />
+ </Badge>
+ ) : null}
<span className="capitalize">{role}</span>
<DropdownMenu>
<DropdownMenuTrigger
@@ -110,6 +129,32 @@ export function UserRow({
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
+ {banned ? (
+ <DropdownMenuItem
+ onClick={() => {
+ startTransition(async () => {
+ await unbanUser.executeAsync({ userId });
+ });
+ }}
+ disabled={!canBan}
+ >
+ <Icon>
+ <UserCheckIcon />
+ </Icon>
+ <Trans i18nKey="unbanUser" defaults="Unban user" />
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={() => {
+ banDialog.trigger();
+ }}
+ disabled={!canBan}
+ >
+ <BanIcon className="size-4" />
+ <Trans i18nKey="banUser" defaults="Ban user" />
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
className="text-destructive"
onClick={async () => {
@@ -124,6 +169,7 @@ export function UserRow({
</DropdownMenu>
</div>
</StackedListItem>
+ <BanUserDialog {...banDialog.dialogProps} userId={userId} email={email} />
<DeleteUserDialog
{...deleteDialog.dialogProps}
userId={userId}
diff --git a/apps/web/src/features/moderation/mutations.ts b/apps/web/src/features/moderation/mutations.ts
index 175fc414b..bbba7b4f3 100644
--- a/apps/web/src/features/moderation/mutations.ts
+++ b/apps/web/src/features/moderation/mutations.ts
@@ -1,12 +1,12 @@
import "server-only";
import { openai } from "@ai-sdk/openai";
-import { prisma } from "@rallly/database";
import { sendRawEmail } from "@rallly/emails";
import { createLogger } from "@rallly/logger";
import { generateText } from "ai";
import { after } from "next/server";
import { env } from "@/env";
+import { banUserAsSystem } from "@/features/user/mutations";
import type { ModerationResult, ModerationVerdict } from "./types";
import { containsSuspiciousPatterns } from "./utils";
@@ -132,13 +132,9 @@ export async function moderateContent({
if (containsBannedDomain(textToModerate)) {
logger.warn({ userId }, "Banned domain detected, banning user");
after(() =>
- prisma.user.update({
- where: { id: userId },
- data: {
- banned: true,
- bannedAt: new Date(),
- banReason: "Automatic ban: banned domain detected in content",
- },
+ banUserAsSystem({
+ userId,
+ reason: "Automatic ban: banned domain detected in content",
}),
);
return {
diff --git a/apps/web/src/features/user/ability.ts b/apps/web/src/features/user/ability.ts
index 0dcc198a7..24b60d50e 100644
--- a/apps/web/src/features/user/ability.ts
+++ b/apps/web/src/features/user/ability.ts
@@ -84,6 +84,10 @@ function defineAbilityForAdmin(
can("update", "User", ["role"]);
// Cannot update their own role
cannot("update", "User", ["role"], { id: user.id });
+ // Can ban/unban any user
+ can("update", "User", ["banned"]);
+ // Cannot ban themselves
+ cannot("update", "User", ["banned"], { id: user.id });
// Can delete any user
can("delete", "User");
// Cannot delete their own account
diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.ts
index c9873646d..faef145d0 100644
--- a/apps/web/src/features/user/actions.ts
+++ b/apps/web/src/features/user/actions.ts
@@ -3,7 +3,12 @@ import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
import { headers } from "next/headers";
import * as z from "zod";
-import { updateUserImage, updateUserName } from "@/features/user/mutations";
+import {
+ banUser,
+ unbanUser,
+ updateUserImage,
+ updateUserName,
+} from "@/features/user/mutations";
import authLib from "@/lib/auth";
import { timeFormatSchema, weekStartSchema } from "@/lib/datetime/schema";
import { AppError } from "@/lib/errors/app-error";
@@ -157,6 +162,83 @@ export const changeRoleAction = adminActionClient
});
});
+export const banUserAction = adminActionClient
+ .metadata({ actionName: "ban_user" })
+ .inputSchema(
+ z.object({
+ userId: z.string(),
+ reason: z.string().trim().max(500).optional(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ const { userId, reason } = parsedInput;
+
+ const targetUser = await prisma.user.findUnique({
+ where: { id: userId },
+ });
+
+ if (!targetUser) {
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: `User ${userId} not found`,
+ });
+ }
+
+ if (targetUser.banned) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "User is already banned",
+ });
+ }
+
+ if (ctx.ability.cannot("update", subject("User", targetUser), "banned")) {
+ throw new AppError({
+ code: "UNAUTHORIZED",
+ message: "Current user is not authorized to ban this user",
+ });
+ }
+
+ await banUser({ userId, reason: reason || undefined });
+ });
+
+export const unbanUserAction = adminActionClient
+ .metadata({ actionName: "unban_user" })
+ .inputSchema(
+ z.object({
+ userId: z.string(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ const { userId } = parsedInput;
+
+ const targetUser = await prisma.user.findUnique({
+ where: { id: userId },
+ });
+
+ if (!targetUser) {
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: `User ${userId} not found`,
+ });
+ }
+
+ if (!targetUser.banned) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "User is not banned",
+ });
+ }
+
+ if (ctx.ability.cannot("update", subject("User", targetUser), "banned")) {
+ throw new AppError({
+ code: "UNAUTHORIZED",
+ message: "Current user is not authorized to unban this user",
+ });
+ }
+
+ await unbanUser({ userId });
+ });
+
export const deleteUserAction = adminActionClient
.metadata({ actionName: "delete_user" })
.inputSchema(
diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.ts
index 29cfc52e2..3d5118d07 100644
--- a/apps/web/src/features/user/mutations.ts
+++ b/apps/web/src/features/user/mutations.ts
@@ -79,6 +79,68 @@ export async function updateUserImage({
revalidateTag(userProfileTag(userId), "max");
}
+// Bans must go through Better-Auth rather than Prisma so the user's sessions
+// are actually revoked — with secondary storage enabled, sessions live in
+// Redis, not the Session table, and only Better-Auth's own APIs delete those
+// keys. A bare `banned: true` write leaves the user logged in until their
+// session expires.
+
+export async function banUser({
+ userId,
+ reason,
+}: {
+ userId: string;
+ reason?: string;
+}) {
+ await authLib.api.banUser({
+ body: { userId, banReason: reason },
+ headers: await headers(),
+ });
+
+ await prisma.user.update({
+ where: { id: userId },
+ data: { bannedAt: new Date() },
+ });
+}
+
+export async function unbanUser({ userId }: { userId: string }) {
+ await authLib.api.unbanUser({
+ body: { userId },
+ headers: await headers(),
+ });
+
+ await prisma.user.update({
+ where: { id: userId },
+ data: { bannedAt: null },
+ });
+}
+
+// For bans issued without an admin session (e.g. the moderation auto-ban).
+// Mirrors what authLib.api.banUser does internally, minus the permission
+// checks — authorization is the caller's responsibility.
+export async function banUserAsSystem({
+ userId,
+ reason,
+}: {
+ userId: string;
+ reason: string;
+}) {
+ const { internalAdapter } = await authLib.$context;
+
+ await internalAdapter.updateUser(userId, {
+ banned: true,
+ banReason: reason,
+ updatedAt: new Date(),
+ });
+
+ await internalAdapter.deleteSessions(userId);
+
+ await prisma.user.update({
+ where: { id: userId },
+ data: { bannedAt: new Date() },
+ });
+}
+
export async function setActiveSpace({
userId,
spaceId,