Files
property-management-network/app/actions/admin.ts
T
Leon SerfatyandClaude Opus 4.8 5495b94924 Deploy on DigitalOcean App Platform (GitHub-source build) + consolidate audit-fixes
Deploy config:
- .do/app.yaml: build the Dockerfile directly from GitHub (deploy_on_push) instead
  of a pre-built DOCR image; NEXT_PUBLIC_* set RUN_AND_BUILD_TIME with the
  propertymanagement.network domain so they bake into the client bundle; add
  custom domains block (apex + www); wire Sentry DSN (server + browser).

Included pending work from the audit-fixes branch:
- AI provider abstraction (OpenAI/Anthropic, admin-selectable; Anthropic default)
- Per-landlord e-signature (DocuSign OAuth + Dropbox Sign) + migration 0010
- Outbound webhooks / Zapier integration
- PayPal removal (Stripe-only billing)
- Storage hardening (fail-loud when Spaces unconfigured), security fixes

Verified: full production Docker build (same build-args as DO) passes clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 04:45:24 -04:00

181 lines
6.4 KiB
TypeScript

"use server"
import { headers } from "next/headers"
import { redirect } from "next/navigation"
import { revalidatePath } from "next/cache"
import { eq } from "drizzle-orm"
import { z } from "zod"
import { getAdminSession } from "@/lib/session"
import { logAdminAction } from "@/lib/admin/audit"
import { setMaintenanceMode } from "@/lib/settings"
import { setAiProvider, type AiProvider } from "@/lib/ai/provider"
import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { profiles, user as userTable } from "@/lib/db/schema"
// ── gate ────────────────────────────────────────────────────────────────────
// Every server action re-verifies the caller is an admin. NEVER skip — these
// mutate any user's data and bypass user_id scoping.
async function guard() {
const a = await getAdminSession()
if (!a) throw new Error("Forbidden")
return a
}
const planSchema = z.enum(["starter", "pro", "landlord", "lifetime"])
// ── change plan ─────────────────────────────────────────────────────────────
export async function changeUserPlan(userId: string, plan: string) {
const a = await guard()
const nextPlan = planSchema.parse(plan)
const existing = await db.query.profiles.findFirst({ where: eq(profiles.id, userId) })
const oldPlan = existing?.plan ?? null
await db.update(profiles).set({ plan: nextPlan }).where(eq(profiles.id, userId))
await logAdminAction({
adminId: a.user.id,
action: "plan_change",
targetUserId: userId,
metadata: { from: oldPlan, to: nextPlan },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true }
}
// ── ban ─────────────────────────────────────────────────────────────────────
export async function banUser(userId: string, reason?: string) {
const a = await guard()
if (userId === a.user.id) throw new Error("You cannot ban yourself")
await auth.api.banUser({
body: { userId, banReason: reason || "Banned by admin" },
headers: await headers(),
})
await logAdminAction({
adminId: a.user.id,
action: "ban",
targetUserId: userId,
metadata: { reason: reason || "Banned by admin" },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true }
}
// ── unban ───────────────────────────────────────────────────────────────────
export async function unbanUser(userId: string) {
const a = await guard()
await auth.api.unbanUser({
body: { userId },
headers: await headers(),
})
await logAdminAction({
adminId: a.user.id,
action: "unban",
targetUserId: userId,
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true }
}
// ── impersonate ─────────────────────────────────────────────────────────────
export async function impersonateUser(userId: string) {
const a = await guard()
if (userId === a.user.id) throw new Error("You cannot impersonate yourself")
await auth.api.impersonateUser({
body: { userId },
headers: await headers(),
})
await logAdminAction({
adminId: a.user.id,
action: "impersonate",
targetUserId: userId,
})
redirect("/dashboard")
}
// ── delete ──────────────────────────────────────────────────────────────────
export async function deleteUser(userId: string) {
const a = await guard()
if (userId === a.user.id) throw new Error("You cannot delete yourself")
await auth.api.removeUser({
body: { userId },
headers: await headers(),
})
await logAdminAction({
adminId: a.user.id,
action: "delete_user",
targetUserId: userId,
})
redirect("/admin/users")
}
// ── mark email verified ─────────────────────────────────────────────────────
export async function markEmailVerified(userId: string) {
const a = await guard()
await db.update(userTable).set({ emailVerified: true }).where(eq(userTable.id, userId))
await logAdminAction({
adminId: a.user.id,
action: "resend_verification",
targetUserId: userId,
metadata: { markedVerified: true },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true }
}
// ── site maintenance mode ─────────────────────────────────────────────────────
// Toggles the site-wide maintenance flag (persisted in app_settings). When on,
// the marketing site and dashboard show a maintenance page to everyone except
// admins. Revalidates the whole app so the change takes effect immediately.
export async function setSiteMaintenance(enabled: boolean, message?: string) {
const a = await guard()
const trimmed = message?.trim() || null
await setMaintenanceMode({ enabled: Boolean(enabled), message: trimmed })
await logAdminAction({
adminId: a.user.id,
action: "maintenance_mode",
metadata: { enabled: Boolean(enabled), message: trimmed },
})
revalidatePath("/", "layout")
return { ok: true }
}
// ── AI provider ───────────────────────────────────────────────────────────────
// Chooses which LLM provider powers all AI features (OpenAI or Anthropic/Claude),
// persisted in app_settings. Applies immediately to every AI route.
export async function setAiProviderAction(provider: string) {
const a = await guard()
if (provider !== "openai" && provider !== "anthropic") throw new Error("Invalid AI provider")
await setAiProvider(provider as AiProvider)
await logAdminAction({
adminId: a.user.id,
action: "ai_provider",
metadata: { provider },
})
revalidatePath("/admin/system")
return { ok: true }
}