import type { Context, Next } from "hono"; import type { AppContext } from "../lib/app-context.js"; import type { Variables } from "../types.js"; import { handleRouteError } from "../lib/route-errors.js"; import { getActiveBans } from "../routes/helpers.js"; /** * Middleware that checks if the authenticated user is banned. * * Must be used AFTER requireAuth (depends on c.get("user") being set). * Fails closed: if the ban check fails, the request is denied. * * Usage: * app.post("/api/topics", requireAuth(ctx), requireNotBanned(ctx), async (c) => { ... }); */ export function requireNotBanned(ctx: AppContext) { return async (c: Context<{ Variables: Variables }>, next: Next) => { const user = c.get("user"); if (!user) { return c.json({ error: "Authentication required" }, 401); } try { const bannedUsers = await getActiveBans(ctx.db, [user.did]); if (bannedUsers.has(user.did)) { return c.json({ error: "You are banned from this forum" }, 403); } } catch (error) { return handleRouteError(c, error, "Unable to verify ban status", { operation: `${c.req.method} ${c.req.path} - ban check`, logger: ctx.logger, userId: user.did, }); } await next(); }; }