Add Roles & Admin/Super-Admin interface
Per organized-ideas.md §6: role assignment, account ban/unban/delete, and direct Admin/Super-Admin CRUD of public catalog entries outside the submission workflow. Backend: - list_users_for_admin(): Super-Admin-gated SECURITY DEFINER function joining profiles + auth.users (username, email, role, banned_until) — auth.users isn't exposed through PostgREST, so this is the only way to list accounts at all. - New Edge Function admin-user-action (ban/unban/delete), using @supabase/server's `auth: 'user'` mode to verify the caller's JWT, then Supabase Auth's Admin API for the actual mutation. This is deliberately an Edge Function rather than a Postgres function like everything else in this codebase: touching auth.users needs the Admin API, the stable documented interface, not a direct write to a schema Supabase manages internally. Self-action guard; verify_jwt = true at the gateway on top of the function's own JWT verification. - 5 new pgTAP tests (43/43 total) for list_users_for_admin (Super-Admin-only, even regular Admins get 42501). - CatalogRepository gains admin* methods (direct edit of a public port/cable/ device entry, plus adminUnpublish which flips is_public rather than deleting) — the update methods were already ownership-agnostic (RLS's is_admin() clause is what actually permits it), so these are thin aliases, not duplicated logic. Frontend: - authStore/AdminUserRepository: minimal role plumbing, shared UserRole type. - adminUserStore + AdminUsersModal: list/role-dropdown/ban/unban/delete, gated to Super Admin only via a new "Manage Users" TopBar button. - PortTypeManager/CableTypeManager/DevicePalette: built-in entries now show direct "Edit"/"Unpublish" for Admins (regular Admin included, per §6's capability table — not Super-Admin-exclusive) instead of "Suggest edit"; unpublish reuses the review-queue's impact-check RPC before confirming. - DeviceTemplateEditor gains an `adminMode` save path alongside its existing submissionMode/resubmitId ones. Verified: tsc -b and oxlint clean; supabase db reset + 43/43 pgTAP tests pass; confirmed both new privileged endpoints (the SQL function and the Edge Function) actually work through the real REST API via live curl calls — signup, email confirm, role promotion, ban/unban/delete round trips, self-action guard, non-super-admin rejection, and verify_jwt=true compatibility all exercised directly, not just asserted.
This commit is contained in:
@@ -0,0 +1,137 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import type { AdminUserSummary, UserRole } from '../../data/AdminUserRepository'
|
||||||
|
import { useAdminUserStore } from '../../state/adminUserStore'
|
||||||
|
import { useAuthStore } from '../../state/authStore'
|
||||||
|
import Modal from '../common/Modal'
|
||||||
|
|
||||||
|
const ROLE_OPTIONS: UserRole[] = ['regular', 'admin', 'super_admin']
|
||||||
|
|
||||||
|
function formatDate(iso: string): string {
|
||||||
|
return new Date(iso).toLocaleDateString(undefined, { dateStyle: 'medium' })
|
||||||
|
}
|
||||||
|
|
||||||
|
function isBanned(user: AdminUserSummary): boolean {
|
||||||
|
return !!user.bannedUntil && new Date(user.bannedUntil).getTime() > Date.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminUsersModal({ onClose }: { onClose: () => void }) {
|
||||||
|
const currentUserId = useAuthStore((s) => s.userId)
|
||||||
|
const users = useAdminUserStore((s) => s.users)
|
||||||
|
const loadUsers = useAdminUserStore((s) => s.loadUsers)
|
||||||
|
const updateRole = useAdminUserStore((s) => s.updateRole)
|
||||||
|
const banUser = useAdminUserStore((s) => s.banUser)
|
||||||
|
const unbanUser = useAdminUserStore((s) => s.unbanUser)
|
||||||
|
const deleteUser = useAdminUserStore((s) => s.deleteUser)
|
||||||
|
const [busyId, setBusyId] = useState<string | null>(null)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadUsers()
|
||||||
|
}, [loadUsers])
|
||||||
|
|
||||||
|
const runAction = async (userId: string, action: () => Promise<void>) => {
|
||||||
|
setError(null)
|
||||||
|
setBusyId(userId)
|
||||||
|
try {
|
||||||
|
await action()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Something went wrong.')
|
||||||
|
} finally {
|
||||||
|
setBusyId(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRoleChange = (user: AdminUserSummary, role: UserRole) => {
|
||||||
|
if (user.id === currentUserId && role !== 'super_admin') {
|
||||||
|
const confirmed = window.confirm(
|
||||||
|
`Change your own role to "${role}"? You'll lose Super Admin access immediately — another Super Admin (or direct DB access) would be needed to undo this.`,
|
||||||
|
)
|
||||||
|
if (!confirmed) return
|
||||||
|
}
|
||||||
|
runAction(user.id, () => updateRole(user.id, role))
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleBanToggle = (user: AdminUserSummary) => {
|
||||||
|
const banned = isBanned(user)
|
||||||
|
const confirmed = window.confirm(
|
||||||
|
banned ? `Unban "${user.username}"? They'll be able to sign in again.` : `Ban "${user.username}"? This blocks sign-in but keeps their data intact — reversible.`,
|
||||||
|
)
|
||||||
|
if (!confirmed) return
|
||||||
|
runAction(user.id, () => (banned ? unbanUser(user.id) : banUser(user.id)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = (user: AdminUserSummary) => {
|
||||||
|
const confirmed = window.confirm(
|
||||||
|
`Permanently delete "${user.username}"? This deletes their account AND all their diagrams and private catalog entries. This cannot be undone.`,
|
||||||
|
)
|
||||||
|
if (!confirmed) return
|
||||||
|
runAction(user.id, () => deleteUser(user.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal title="Manage Users" onClose={onClose} width="max-w-2xl">
|
||||||
|
{error && <p className="mb-2 rounded bg-red-50 px-2 py-1.5 text-xs text-red-700">{error}</p>}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{users.map((user) => {
|
||||||
|
const busy = busyId === user.id
|
||||||
|
const self = user.id === currentUserId
|
||||||
|
const banned = isBanned(user)
|
||||||
|
return (
|
||||||
|
<div key={user.id} className="flex items-center justify-between gap-2 rounded border border-slate-200 bg-white px-2.5 py-1.5 text-xs">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className="font-medium text-slate-700">{user.username}</span>
|
||||||
|
{self && (
|
||||||
|
<span className="rounded bg-indigo-50 px-1.5 py-0.5 text-[10px] font-medium text-indigo-600">You</span>
|
||||||
|
)}
|
||||||
|
{banned && (
|
||||||
|
<span className="rounded bg-red-50 px-1.5 py-0.5 text-[10px] font-medium text-red-600">Banned</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="truncate text-[10px] text-slate-400">
|
||||||
|
{user.email} · joined {formatDate(user.createdAt)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex shrink-0 items-center gap-1.5">
|
||||||
|
<select
|
||||||
|
value={user.role}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) => handleRoleChange(user, e.target.value as UserRole)}
|
||||||
|
className="rounded border border-slate-300 px-1 py-1 text-[11px] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{ROLE_OPTIONS.map((r) => (
|
||||||
|
<option key={r} value={r}>
|
||||||
|
{r}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
onClick={() => handleBanToggle(user)}
|
||||||
|
disabled={busy || self}
|
||||||
|
title={self ? "You can't ban your own account" : undefined}
|
||||||
|
className="rounded bg-slate-100 px-2 py-1 text-[11px] font-medium text-slate-600 hover:bg-amber-50 hover:text-amber-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{banned ? 'Unban' : 'Ban'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(user)}
|
||||||
|
disabled={busy || self}
|
||||||
|
title={self ? "You can't delete your own account" : undefined}
|
||||||
|
className="rounded bg-slate-100 px-2 py-1 text-[11px] font-medium text-slate-600 hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-40"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{users.length === 0 && <p className="py-2 text-center text-xs italic text-slate-400">No users found.</p>}
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 flex justify-end border-t border-slate-100 pt-3">
|
||||||
|
<button onClick={onClose} className="rounded px-3 py-1.5 text-xs text-slate-600 hover:bg-slate-100">
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { useAdminReviewStore } from '../../state/adminReviewStore'
|
|||||||
import { useAuthStore } from '../../state/authStore'
|
import { useAuthStore } from '../../state/authStore'
|
||||||
import { useProjectStore } from '../../state/projectStore'
|
import { useProjectStore } from '../../state/projectStore'
|
||||||
import { useSubmissionStore } from '../../state/submissionStore'
|
import { useSubmissionStore } from '../../state/submissionStore'
|
||||||
|
import AdminUsersModal from '../admin/AdminUsersModal'
|
||||||
import AdminReviewModal from '../submissions/AdminReviewModal'
|
import AdminReviewModal from '../submissions/AdminReviewModal'
|
||||||
import MySubmissionsModal from '../submissions/MySubmissionsModal'
|
import MySubmissionsModal from '../submissions/MySubmissionsModal'
|
||||||
import DiagramManagerModal from './DiagramManagerModal'
|
import DiagramManagerModal from './DiagramManagerModal'
|
||||||
@@ -37,11 +38,13 @@ export default function TopBar() {
|
|||||||
const username = useAuthStore((s) => s.username)
|
const username = useAuthStore((s) => s.username)
|
||||||
const role = useAuthStore((s) => s.role)
|
const role = useAuthStore((s) => s.role)
|
||||||
const isAdmin = role === 'admin' || role === 'super_admin'
|
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||||
|
const isSuperAdmin = role === 'super_admin'
|
||||||
const adminPendingCount = useAdminReviewStore((s) => s.allSubmissions.filter((sub) => sub.status === 'pending').length)
|
const adminPendingCount = useAdminReviewStore((s) => s.allSubmissions.filter((sub) => sub.status === 'pending').length)
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
const [diagramManagerOpen, setDiagramManagerOpen] = useState(false)
|
const [diagramManagerOpen, setDiagramManagerOpen] = useState(false)
|
||||||
const [submissionsOpen, setSubmissionsOpen] = useState(false)
|
const [submissionsOpen, setSubmissionsOpen] = useState(false)
|
||||||
const [adminReviewOpen, setAdminReviewOpen] = useState(false)
|
const [adminReviewOpen, setAdminReviewOpen] = useState(false)
|
||||||
|
const [adminUsersOpen, setAdminUsersOpen] = useState(false)
|
||||||
|
|
||||||
const pendingSubmissionCount = useMemo(
|
const pendingSubmissionCount = useMemo(
|
||||||
() => mySubmissions.filter((s) => s.status === 'pending').length,
|
() => mySubmissions.filter((s) => s.status === 'pending').length,
|
||||||
@@ -121,6 +124,14 @@ export default function TopBar() {
|
|||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{isSuperAdmin && (
|
||||||
|
<button
|
||||||
|
onClick={() => setAdminUsersOpen(true)}
|
||||||
|
className="rounded px-2.5 py-1.5 text-xs text-slate-600 hover:bg-slate-100"
|
||||||
|
>
|
||||||
|
Manage Users
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button onClick={handleImportClick} className="rounded px-2.5 py-1.5 text-xs text-slate-600 hover:bg-slate-100">
|
<button onClick={handleImportClick} className="rounded px-2.5 py-1.5 text-xs text-slate-600 hover:bg-slate-100">
|
||||||
Import
|
Import
|
||||||
</button>
|
</button>
|
||||||
@@ -142,6 +153,7 @@ export default function TopBar() {
|
|||||||
{diagramManagerOpen && <DiagramManagerModal onClose={() => setDiagramManagerOpen(false)} />}
|
{diagramManagerOpen && <DiagramManagerModal onClose={() => setDiagramManagerOpen(false)} />}
|
||||||
{submissionsOpen && <MySubmissionsModal onClose={() => setSubmissionsOpen(false)} />}
|
{submissionsOpen && <MySubmissionsModal onClose={() => setSubmissionsOpen(false)} />}
|
||||||
{adminReviewOpen && <AdminReviewModal onClose={() => setAdminReviewOpen(false)} />}
|
{adminReviewOpen && <AdminReviewModal onClose={() => setAdminReviewOpen(false)} />}
|
||||||
|
{adminUsersOpen && <AdminUsersModal onClose={() => setAdminUsersOpen(false)} />}
|
||||||
</header>
|
</header>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { useMemo, useState } from 'react'
|
|||||||
import { allCableTypes, allPortTypes } from '../../domain/project'
|
import { allCableTypes, allPortTypes } from '../../domain/project'
|
||||||
import type { CableType, PortType } from '../../domain/types'
|
import type { CableType, PortType } from '../../domain/types'
|
||||||
import { cableTypeToRow } from '../../data/catalogRowMapping'
|
import { cableTypeToRow } from '../../data/catalogRowMapping'
|
||||||
|
import { useAdminReviewStore } from '../../state/adminReviewStore'
|
||||||
|
import { useAuthStore } from '../../state/authStore'
|
||||||
import { useCatalogStore } from '../../state/catalogStore'
|
import { useCatalogStore } from '../../state/catalogStore'
|
||||||
import { useSubmissionStore } from '../../state/submissionStore'
|
import { useSubmissionStore } from '../../state/submissionStore'
|
||||||
import { resolveCableTypeFields, type CableTypeFormFields } from './cableTypeFormFields'
|
import { resolveCableTypeFields, type CableTypeFormFields } from './cableTypeFormFields'
|
||||||
@@ -129,11 +131,17 @@ export default function CableTypesPanel() {
|
|||||||
const catalog = useCatalogStore((s) => s.catalog)
|
const catalog = useCatalogStore((s) => s.catalog)
|
||||||
const addCustomCableType = useCatalogStore((s) => s.addCustomCableType)
|
const addCustomCableType = useCatalogStore((s) => s.addCustomCableType)
|
||||||
const updateCustomCableType = useCatalogStore((s) => s.updateCustomCableType)
|
const updateCustomCableType = useCatalogStore((s) => s.updateCustomCableType)
|
||||||
|
const adminUpdateCableType = useCatalogStore((s) => s.adminUpdateCableType)
|
||||||
|
const adminUnpublish = useCatalogStore((s) => s.adminUnpublish)
|
||||||
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
||||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||||
|
const getUsageImpact = useAdminReviewStore((s) => s.getUsageImpact)
|
||||||
|
const role = useAuthStore((s) => s.role)
|
||||||
|
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||||
const [creating, setCreating] = useState(false)
|
const [creating, setCreating] = useState(false)
|
||||||
const [editingId, setEditingId] = useState<string | null>(null)
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
const [suggestingId, setSuggestingId] = useState<string | null>(null)
|
const [suggestingId, setSuggestingId] = useState<string | null>(null)
|
||||||
|
const [adminEditingId, setAdminEditingId] = useState<string | null>(null)
|
||||||
|
|
||||||
const portTypes = useMemo(
|
const portTypes = useMemo(
|
||||||
() => [...allPortTypes(catalog)].sort((a, b) => a.name.localeCompare(b.name)),
|
() => [...allPortTypes(catalog)].sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
@@ -185,6 +193,24 @@ export default function CableTypesPanel() {
|
|||||||
setSuggestingId(null)
|
setSuggestingId(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleAdminSave = (id: string, fields: CableTypeFormFields) => {
|
||||||
|
const resolved = resolveCableTypeFields(fields, portTypes)
|
||||||
|
if (!resolved) return
|
||||||
|
adminUpdateCableType(id, resolved)
|
||||||
|
setAdminEditingId(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUnpublish = async (ct: CableType) => {
|
||||||
|
const impact = await getUsageImpact('cable_type', ct.id)
|
||||||
|
const impactNote =
|
||||||
|
impact.diagramCount > 0
|
||||||
|
? `\n\nUsed in ${impact.diagramCount} diagram${impact.diagramCount === 1 ? '' : 's'}: ${impact.sample.map((s) => `${s.name} (${s.ownerUsername})`).join(', ')}${impact.diagramCount > impact.sample.length ? ', …' : ''}. Existing diagrams keep working — this only removes it from new use.`
|
||||||
|
: '\n\nNot currently used in any diagram.'
|
||||||
|
const confirmed = window.confirm(`Unpublish "${ct.name}" from the public catalog?${impactNote}`)
|
||||||
|
if (!confirmed) return
|
||||||
|
adminUnpublish('cable_type', ct.id)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -263,22 +289,52 @@ export default function CableTypesPanel() {
|
|||||||
Built-in ({builtInTypes.length})
|
Built-in ({builtInTypes.length})
|
||||||
</h4>
|
</h4>
|
||||||
<div className="max-h-64 space-y-1 overflow-y-auto rounded border border-slate-200 p-1.5">
|
<div className="max-h-64 space-y-1 overflow-y-auto rounded border border-slate-200 p-1.5">
|
||||||
{builtInTypes.map((ct) =>
|
{builtInTypes.map((ct) => {
|
||||||
suggestingId === ct.id ? (
|
if (isAdmin && adminEditingId === ct.id) {
|
||||||
<div key={ct.id} className="mb-1.5">
|
return (
|
||||||
<CableTypeForm
|
<div key={ct.id} className="mb-1.5">
|
||||||
initial={ct}
|
<CableTypeForm
|
||||||
portTypes={portTypes}
|
initial={ct}
|
||||||
onCancel={() => setSuggestingId(null)}
|
portTypes={portTypes}
|
||||||
onSave={(fields) => handleSuggestEdit(ct.id, fields)}
|
onCancel={() => setAdminEditingId(null)}
|
||||||
/>
|
onSave={(fields) => handleAdminSave(ct.id, fields)}
|
||||||
</div>
|
/>
|
||||||
) : (
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!isAdmin && suggestingId === ct.id) {
|
||||||
|
return (
|
||||||
|
<div key={ct.id} className="mb-1.5">
|
||||||
|
<CableTypeForm
|
||||||
|
initial={ct}
|
||||||
|
portTypes={portTypes}
|
||||||
|
onCancel={() => setSuggestingId(null)}
|
||||||
|
onSave={(fields) => handleSuggestEdit(ct.id, fields)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
<div key={ct.id} className="flex items-center justify-between gap-2 px-1 py-0.5 text-[11px] text-slate-500">
|
<div key={ct.id} className="flex items-center justify-between gap-2 px-1 py-0.5 text-[11px] text-slate-500">
|
||||||
<span className="min-w-0 truncate">
|
<span className="min-w-0 truncate">
|
||||||
{ct.name} <span className="text-slate-400">· {describeEnds(ct)}</span>
|
{ct.name} <span className="text-slate-400">· {describeEnds(ct)}</span>
|
||||||
</span>
|
</span>
|
||||||
{pendingEntityIds.has(ct.id) ? (
|
{isAdmin ? (
|
||||||
|
<div className="flex shrink-0 items-center gap-1">
|
||||||
|
<button
|
||||||
|
onClick={() => setAdminEditingId(ct.id)}
|
||||||
|
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-indigo-100 hover:text-indigo-700"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleUnpublish(ct)}
|
||||||
|
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-red-50 hover:text-red-600"
|
||||||
|
>
|
||||||
|
Unpublish
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : pendingEntityIds.has(ct.id) ? (
|
||||||
<span className="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-600">
|
<span className="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-600">
|
||||||
Edit pending review
|
Edit pending review
|
||||||
</span>
|
</span>
|
||||||
@@ -291,11 +347,13 @@ export default function CableTypesPanel() {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
),
|
)
|
||||||
)}
|
})}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-[10px] text-slate-400">
|
<p className="mt-1 text-[10px] text-slate-400">
|
||||||
Built-in cable types can't be edited directly — "Suggest edit" sends a proposed change to Admins for review.
|
{isAdmin
|
||||||
|
? 'As an Admin, you can edit or unpublish public cable types directly.'
|
||||||
|
: 'Built-in cable types can\'t be edited directly — "Suggest edit" sends a proposed change to Admins for review.'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { useMemo, useState } from 'react'
|
|||||||
import { deviceTemplateToRow } from '../../data/catalogRowMapping'
|
import { deviceTemplateToRow } from '../../data/catalogRowMapping'
|
||||||
import { allDeviceCategories, allDeviceTemplates, hiddenDeviceTemplates } from '../../domain/project'
|
import { allDeviceCategories, allDeviceTemplates, hiddenDeviceTemplates } from '../../domain/project'
|
||||||
import type { DeviceTemplate } from '../../domain/types'
|
import type { DeviceTemplate } from '../../domain/types'
|
||||||
|
import { useAdminReviewStore } from '../../state/adminReviewStore'
|
||||||
|
import { useAuthStore } from '../../state/authStore'
|
||||||
import { useCatalogStore } from '../../state/catalogStore'
|
import { useCatalogStore } from '../../state/catalogStore'
|
||||||
import { useProjectStore } from '../../state/projectStore'
|
import { useProjectStore } from '../../state/projectStore'
|
||||||
import { useSubmissionStore } from '../../state/submissionStore'
|
import { useSubmissionStore } from '../../state/submissionStore'
|
||||||
@@ -10,7 +12,11 @@ import Chevron from '../common/Chevron'
|
|||||||
import ConnectorLibraryModal from './ConnectorLibraryModal'
|
import ConnectorLibraryModal from './ConnectorLibraryModal'
|
||||||
import DeviceTemplateEditor from './DeviceTemplateEditor'
|
import DeviceTemplateEditor from './DeviceTemplateEditor'
|
||||||
|
|
||||||
type EditorTarget = { mode: 'new' } | { mode: 'edit'; template: DeviceTemplate } | { mode: 'suggestEdit'; template: DeviceTemplate }
|
type EditorTarget =
|
||||||
|
| { mode: 'new' }
|
||||||
|
| { mode: 'edit'; template: DeviceTemplate }
|
||||||
|
| { mode: 'suggestEdit'; template: DeviceTemplate }
|
||||||
|
| { mode: 'adminEdit'; template: DeviceTemplate }
|
||||||
|
|
||||||
export default function DevicePalette() {
|
export default function DevicePalette() {
|
||||||
const project = useProjectStore((s) => s.project)
|
const project = useProjectStore((s) => s.project)
|
||||||
@@ -20,8 +26,12 @@ export default function DevicePalette() {
|
|||||||
const removeCustomDeviceTemplate = useCatalogStore((s) => s.removeCustomDeviceTemplate)
|
const removeCustomDeviceTemplate = useCatalogStore((s) => s.removeCustomDeviceTemplate)
|
||||||
const hidePublicDeviceTemplate = useCatalogStore((s) => s.hidePublicDeviceTemplate)
|
const hidePublicDeviceTemplate = useCatalogStore((s) => s.hidePublicDeviceTemplate)
|
||||||
const restorePublicDeviceTemplate = useCatalogStore((s) => s.restorePublicDeviceTemplate)
|
const restorePublicDeviceTemplate = useCatalogStore((s) => s.restorePublicDeviceTemplate)
|
||||||
|
const adminUnpublish = useCatalogStore((s) => s.adminUnpublish)
|
||||||
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
||||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||||
|
const getUsageImpact = useAdminReviewStore((s) => s.getUsageImpact)
|
||||||
|
const role = useAuthStore((s) => s.role)
|
||||||
|
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||||
const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null)
|
const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null)
|
||||||
const [portTypesOpen, setPortTypesOpen] = useState(false)
|
const [portTypesOpen, setPortTypesOpen] = useState(false)
|
||||||
const [hiddenListOpen, setHiddenListOpen] = useState(false)
|
const [hiddenListOpen, setHiddenListOpen] = useState(false)
|
||||||
@@ -99,6 +109,17 @@ export default function DevicePalette() {
|
|||||||
submitForReview('device_template', template.id, deviceTemplateToRow(template))
|
submitForReview('device_template', template.id, deviceTemplateToRow(template))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleUnpublish = async (template: DeviceTemplate) => {
|
||||||
|
const impact = await getUsageImpact('device_template', template.id)
|
||||||
|
const impactNote =
|
||||||
|
impact.diagramCount > 0
|
||||||
|
? `\n\nUsed in ${impact.diagramCount} diagram${impact.diagramCount === 1 ? '' : 's'}: ${impact.sample.map((s) => `${s.name} (${s.ownerUsername})`).join(', ')}${impact.diagramCount > impact.sample.length ? ', …' : ''}. Existing diagrams keep working — this only removes it from new use.`
|
||||||
|
: '\n\nNot currently used in any diagram.'
|
||||||
|
const confirmed = window.confirm(`Unpublish "${template.name}" from the public catalog?${impactNote}`)
|
||||||
|
if (!confirmed) return
|
||||||
|
adminUnpublish('device_template', template.id)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside className="flex h-full w-64 shrink-0 flex-col border-r border-slate-200 bg-slate-50">
|
<aside className="flex h-full w-64 shrink-0 flex-col border-r border-slate-200 bg-slate-50">
|
||||||
<div className="flex items-center justify-between border-b border-slate-200 px-3 py-2">
|
<div className="flex items-center justify-between border-b border-slate-200 px-3 py-2">
|
||||||
@@ -169,6 +190,23 @@ export default function DevicePalette() {
|
|||||||
>
|
>
|
||||||
⇪
|
⇪
|
||||||
</button>
|
</button>
|
||||||
|
) : isAdmin ? (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => setEditorTarget({ mode: 'adminEdit', template })}
|
||||||
|
title="Edit this public device directly"
|
||||||
|
className="rounded bg-slate-100 px-1.5 py-0.5 text-slate-500 hover:bg-indigo-100 hover:text-indigo-700"
|
||||||
|
>
|
||||||
|
✎
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleUnpublish(template)}
|
||||||
|
title="Unpublish from the public catalog"
|
||||||
|
className="rounded bg-slate-100 px-1.5 py-0.5 text-slate-500 hover:bg-red-50 hover:text-red-600"
|
||||||
|
>
|
||||||
|
⛔
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<button
|
<button
|
||||||
onClick={() => setEditorTarget({ mode: 'suggestEdit', template })}
|
onClick={() => setEditorTarget({ mode: 'suggestEdit', template })}
|
||||||
@@ -243,6 +281,7 @@ export default function DevicePalette() {
|
|||||||
<DeviceTemplateEditor
|
<DeviceTemplateEditor
|
||||||
template={editorTarget.mode === 'new' ? undefined : editorTarget.template}
|
template={editorTarget.mode === 'new' ? undefined : editorTarget.template}
|
||||||
submissionMode={editorTarget.mode === 'suggestEdit'}
|
submissionMode={editorTarget.mode === 'suggestEdit'}
|
||||||
|
adminMode={editorTarget.mode === 'adminEdit'}
|
||||||
onClose={() => setEditorTarget(null)}
|
onClose={() => setEditorTarget(null)}
|
||||||
onSaved={(categoryId) => expandCategory(categoryId)}
|
onSaved={(categoryId) => expandCategory(categoryId)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ function nextDraftKey() {
|
|||||||
export default function DeviceTemplateEditor({
|
export default function DeviceTemplateEditor({
|
||||||
template,
|
template,
|
||||||
submissionMode = false,
|
submissionMode = false,
|
||||||
|
adminMode = false,
|
||||||
resubmitId,
|
resubmitId,
|
||||||
onClose,
|
onClose,
|
||||||
onSaved,
|
onSaved,
|
||||||
@@ -34,10 +35,14 @@ export default function DeviceTemplateEditor({
|
|||||||
* a suggested edit for Admin review instead of mutating it directly
|
* a suggested edit for Admin review instead of mutating it directly
|
||||||
* (which RLS wouldn't allow anyway). */
|
* (which RLS wouldn't allow anyway). */
|
||||||
submissionMode?: boolean
|
submissionMode?: boolean
|
||||||
|
/** When true, saves directly to the public entry (organized-ideas.md §6:
|
||||||
|
* Admin/Super-Admin can CRUD public entries without going through the
|
||||||
|
* submission workflow). Takes precedence over `submissionMode`. */
|
||||||
|
adminMode?: boolean
|
||||||
/** When set, saving revises this existing submission (of your own,
|
/** When set, saving revises this existing submission (of your own,
|
||||||
* pending or rejected) instead of creating a new one — see
|
* pending or rejected) instead of creating a new one — see
|
||||||
* MySubmissionsModal's "Edit & resubmit". Takes precedence over
|
* MySubmissionsModal's "Edit & resubmit". Takes precedence over
|
||||||
* `submissionMode` if both are somehow set. */
|
* `submissionMode`/`adminMode` if somehow more than one is set. */
|
||||||
resubmitId?: string
|
resubmitId?: string
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
/** Called with the template's category id right before closing, so the
|
/** Called with the template's category id right before closing, so the
|
||||||
@@ -47,6 +52,7 @@ export default function DeviceTemplateEditor({
|
|||||||
const catalog = useCatalogStore((s) => s.catalog)
|
const catalog = useCatalogStore((s) => s.catalog)
|
||||||
const addCustomDeviceTemplate = useCatalogStore((s) => s.addCustomDeviceTemplate)
|
const addCustomDeviceTemplate = useCatalogStore((s) => s.addCustomDeviceTemplate)
|
||||||
const updateCustomDeviceTemplate = useCatalogStore((s) => s.updateCustomDeviceTemplate)
|
const updateCustomDeviceTemplate = useCatalogStore((s) => s.updateCustomDeviceTemplate)
|
||||||
|
const adminUpdateDeviceTemplate = useCatalogStore((s) => s.adminUpdateDeviceTemplate)
|
||||||
const addCustomPortType = useCatalogStore((s) => s.addCustomPortType)
|
const addCustomPortType = useCatalogStore((s) => s.addCustomPortType)
|
||||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||||
const resubmit = useSubmissionStore((s) => s.resubmit)
|
const resubmit = useSubmissionStore((s) => s.resubmit)
|
||||||
@@ -141,6 +147,8 @@ export default function DeviceTemplateEditor({
|
|||||||
}
|
}
|
||||||
if (resubmitId) {
|
if (resubmitId) {
|
||||||
resubmit(resubmitId, deviceTemplateToRow(fields))
|
resubmit(resubmitId, deviceTemplateToRow(fields))
|
||||||
|
} else if (adminMode && template) {
|
||||||
|
adminUpdateDeviceTemplate(template.id, fields)
|
||||||
} else if (submissionMode && template) {
|
} else if (submissionMode && template) {
|
||||||
submitForReview('device_template', template.id, deviceTemplateToRow(fields))
|
submitForReview('device_template', template.id, deviceTemplateToRow(fields))
|
||||||
} else if (template) {
|
} else if (template) {
|
||||||
@@ -154,7 +162,17 @@ export default function DeviceTemplateEditor({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={resubmitId ? 'Revise Submission' : submissionMode ? 'Suggest an Edit' : template ? 'Edit Custom Device' : 'New Custom Device'}
|
title={
|
||||||
|
resubmitId
|
||||||
|
? 'Revise Submission'
|
||||||
|
: adminMode
|
||||||
|
? 'Edit Public Device'
|
||||||
|
: submissionMode
|
||||||
|
? 'Suggest an Edit'
|
||||||
|
: template
|
||||||
|
? 'Edit Custom Device'
|
||||||
|
: 'New Custom Device'
|
||||||
|
}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
width="max-w-xl"
|
width="max-w-xl"
|
||||||
>
|
>
|
||||||
@@ -350,7 +368,15 @@ export default function DeviceTemplateEditor({
|
|||||||
disabled={!canSave}
|
disabled={!canSave}
|
||||||
className="rounded bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-40"
|
className="rounded bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-40"
|
||||||
>
|
>
|
||||||
{resubmitId ? 'Resubmit' : submissionMode ? 'Submit for review' : template ? 'Save changes' : 'Save device'}
|
{resubmitId
|
||||||
|
? 'Resubmit'
|
||||||
|
: adminMode
|
||||||
|
? 'Save changes'
|
||||||
|
: submissionMode
|
||||||
|
? 'Submit for review'
|
||||||
|
: template
|
||||||
|
? 'Save changes'
|
||||||
|
: 'Save device'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { PORT_CATEGORIES } from '../../domain/constants'
|
|||||||
import { allPortTypes, expandCompatibleFamilyIds } from '../../domain/project'
|
import { allPortTypes, expandCompatibleFamilyIds } from '../../domain/project'
|
||||||
import type { PortType } from '../../domain/types'
|
import type { PortType } from '../../domain/types'
|
||||||
import { portTypeToRow } from '../../data/catalogRowMapping'
|
import { portTypeToRow } from '../../data/catalogRowMapping'
|
||||||
|
import { useAdminReviewStore } from '../../state/adminReviewStore'
|
||||||
|
import { useAuthStore } from '../../state/authStore'
|
||||||
import { useCatalogStore } from '../../state/catalogStore'
|
import { useCatalogStore } from '../../state/catalogStore'
|
||||||
import { useSubmissionStore } from '../../state/submissionStore'
|
import { useSubmissionStore } from '../../state/submissionStore'
|
||||||
|
|
||||||
@@ -105,10 +107,16 @@ export function PortTypeForm({
|
|||||||
export default function PortTypesPanel() {
|
export default function PortTypesPanel() {
|
||||||
const catalog = useCatalogStore((s) => s.catalog)
|
const catalog = useCatalogStore((s) => s.catalog)
|
||||||
const updateCustomPortType = useCatalogStore((s) => s.updateCustomPortType)
|
const updateCustomPortType = useCatalogStore((s) => s.updateCustomPortType)
|
||||||
|
const adminUpdatePortType = useCatalogStore((s) => s.adminUpdatePortType)
|
||||||
|
const adminUnpublish = useCatalogStore((s) => s.adminUnpublish)
|
||||||
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
||||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||||
|
const getUsageImpact = useAdminReviewStore((s) => s.getUsageImpact)
|
||||||
|
const role = useAuthStore((s) => s.role)
|
||||||
|
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||||
const [editingId, setEditingId] = useState<string | null>(null)
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
const [suggestingId, setSuggestingId] = useState<string | null>(null)
|
const [suggestingId, setSuggestingId] = useState<string | null>(null)
|
||||||
|
const [adminEditingId, setAdminEditingId] = useState<string | null>(null)
|
||||||
|
|
||||||
const allTypes = useMemo(
|
const allTypes = useMemo(
|
||||||
() => [...allPortTypes(catalog)].sort((a, b) => a.name.localeCompare(b.name)),
|
() => [...allPortTypes(catalog)].sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
@@ -144,6 +152,22 @@ export default function PortTypesPanel() {
|
|||||||
setSuggestingId(null)
|
setSuggestingId(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleAdminSave = (id: string, fields: Omit<PortType, 'id' | 'custom'>) => {
|
||||||
|
adminUpdatePortType(id, fields)
|
||||||
|
setAdminEditingId(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUnpublish = async (pt: PortType) => {
|
||||||
|
const impact = await getUsageImpact('port_type', pt.id)
|
||||||
|
const impactNote =
|
||||||
|
impact.diagramCount > 0
|
||||||
|
? `\n\nUsed in ${impact.diagramCount} diagram${impact.diagramCount === 1 ? '' : 's'}: ${impact.sample.map((s) => `${s.name} (${s.ownerUsername})`).join(', ')}${impact.diagramCount > impact.sample.length ? ', …' : ''}. Existing diagrams keep working — this only removes it from new use.`
|
||||||
|
: '\n\nNot currently used in any diagram.'
|
||||||
|
const confirmed = window.confirm(`Unpublish "${pt.name}" from the public catalog?${impactNote}`)
|
||||||
|
if (!confirmed) return
|
||||||
|
adminUnpublish('port_type', pt.id)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -213,16 +237,30 @@ export default function PortTypesPanel() {
|
|||||||
Built-in ({builtInTypes.length})
|
Built-in ({builtInTypes.length})
|
||||||
</h4>
|
</h4>
|
||||||
<div className="max-h-64 space-y-1 overflow-y-auto rounded border border-slate-200 p-1.5">
|
<div className="max-h-64 space-y-1 overflow-y-auto rounded border border-slate-200 p-1.5">
|
||||||
{builtInTypes.map((pt) =>
|
{builtInTypes.map((pt) => {
|
||||||
suggestingId === pt.id ? (
|
if (isAdmin && adminEditingId === pt.id) {
|
||||||
<PortTypeForm
|
return (
|
||||||
key={pt.id}
|
<PortTypeForm
|
||||||
portType={pt}
|
key={pt.id}
|
||||||
allTypes={allTypes}
|
portType={pt}
|
||||||
onCancel={() => setSuggestingId(null)}
|
allTypes={allTypes}
|
||||||
onSave={(fields) => handleSuggestEdit(pt.id, fields)}
|
onCancel={() => setAdminEditingId(null)}
|
||||||
/>
|
onSave={(fields) => handleAdminSave(pt.id, fields)}
|
||||||
) : (
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!isAdmin && suggestingId === pt.id) {
|
||||||
|
return (
|
||||||
|
<PortTypeForm
|
||||||
|
key={pt.id}
|
||||||
|
portType={pt}
|
||||||
|
allTypes={allTypes}
|
||||||
|
onCancel={() => setSuggestingId(null)}
|
||||||
|
onSave={(fields) => handleSuggestEdit(pt.id, fields)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
<div key={pt.id} className="flex items-center justify-between gap-2 px-1 py-0.5 text-[11px] text-slate-500">
|
<div key={pt.id} className="flex items-center justify-between gap-2 px-1 py-0.5 text-[11px] text-slate-500">
|
||||||
<span className="min-w-0 truncate">
|
<span className="min-w-0 truncate">
|
||||||
{pt.name}
|
{pt.name}
|
||||||
@@ -230,7 +268,22 @@ export default function PortTypesPanel() {
|
|||||||
<span className="text-slate-400"> · also fits: {describeCompatibility(pt)}</span>
|
<span className="text-slate-400"> · also fits: {describeCompatibility(pt)}</span>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
{pendingEntityIds.has(pt.id) ? (
|
{isAdmin ? (
|
||||||
|
<div className="flex shrink-0 items-center gap-1">
|
||||||
|
<button
|
||||||
|
onClick={() => setAdminEditingId(pt.id)}
|
||||||
|
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-indigo-100 hover:text-indigo-700"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleUnpublish(pt)}
|
||||||
|
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-red-50 hover:text-red-600"
|
||||||
|
>
|
||||||
|
Unpublish
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : pendingEntityIds.has(pt.id) ? (
|
||||||
<span className="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-600">
|
<span className="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-600">
|
||||||
Edit pending review
|
Edit pending review
|
||||||
</span>
|
</span>
|
||||||
@@ -243,11 +296,13 @@ export default function PortTypesPanel() {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
),
|
)
|
||||||
)}
|
})}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-[10px] text-slate-400">
|
<p className="mt-1 text-[10px] text-slate-400">
|
||||||
Built-in connector types can't be edited directly — "Suggest edit" sends a proposed change to Admins for review.
|
{isAdmin
|
||||||
|
? 'As an Admin, you can edit or unpublish public connector types directly.'
|
||||||
|
: 'Built-in connector types can\'t be edited directly — "Suggest edit" sends a proposed change to Admins for review.'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/** A user's role — mirrors `profiles.role`'s check constraint. Defined here
|
||||||
|
* (data layer) rather than in state/authStore.ts so both that store and
|
||||||
|
* this repository share one definition without state importing from data
|
||||||
|
* in the wrong direction. */
|
||||||
|
export type UserRole = 'regular' | 'admin' | 'super_admin'
|
||||||
|
|
||||||
|
export interface AdminUserSummary {
|
||||||
|
id: string
|
||||||
|
username: string
|
||||||
|
email: string
|
||||||
|
role: UserRole
|
||||||
|
/** Set (a future timestamp) while banned; undefined otherwise. */
|
||||||
|
bannedUntil?: string
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Storage abstraction for Super-Admin user management (organized-ideas.md
|
||||||
|
* §6's "CRUD user accounts"). Listing and role changes are plain
|
||||||
|
* RLS/privileged-function reads and writes; ban/unban/delete go through
|
||||||
|
* the admin-user-action Edge Function since those specifically need
|
||||||
|
* Supabase Auth's Admin API — see that function's own header comment for
|
||||||
|
* why this can't just be another SQL function like the rest. */
|
||||||
|
export interface AdminUserRepository {
|
||||||
|
listUsers(): Promise<AdminUserSummary[]>
|
||||||
|
updateRole(userId: string, role: UserRole): Promise<void>
|
||||||
|
/** Reversible — blocks login without touching the account's data. */
|
||||||
|
banUser(userId: string): Promise<void>
|
||||||
|
unbanUser(userId: string): Promise<void>
|
||||||
|
/** Irreversible — cascades to the user's profile, diagrams, and owned
|
||||||
|
* private catalog entries via their existing foreign keys. */
|
||||||
|
deleteUser(userId: string): Promise<void>
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { CatalogEntityType } from './SubmissionRepository'
|
||||||
import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, PortType } from '../domain/types'
|
import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, PortType } from '../domain/types'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -7,10 +8,14 @@ import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, PortType }
|
|||||||
* entries plus their own private ones); RLS does that filtering server-side,
|
* entries plus their own private ones); RLS does that filtering server-side,
|
||||||
* so implementations don't need to filter client-side.
|
* so implementations don't need to filter client-side.
|
||||||
*
|
*
|
||||||
* Only covers the "read + manage your own private entries" surface for now.
|
* The `add*`/`update*` methods always create or edit an `is_public = false`
|
||||||
* Submitting a private entry for public review/promotion is a separate,
|
* row you own — that's the regular-user "own private catalog" surface.
|
||||||
* not-yet-built workflow (organized-ideas.md §3/§9) — these `add*`/`update*`
|
* Getting an entry into the public catalog otherwise goes through the
|
||||||
* methods always create or edit is_public = false rows you own.
|
* submission/review workflow (organized-ideas.md §3), except for the
|
||||||
|
* `admin*` methods below: per §6's capability table, an Admin/Super-Admin
|
||||||
|
* can also CRUD public entries directly, without a submission — those
|
||||||
|
* bypass ownership entirely (RLS's `is_admin()` clause is what actually
|
||||||
|
* allows it) and only ever touch already-public rows.
|
||||||
*/
|
*/
|
||||||
export interface CatalogRepository {
|
export interface CatalogRepository {
|
||||||
/** Everything visible to the current user: public entries plus their own private ones. */
|
/** Everything visible to the current user: public entries plus their own private ones. */
|
||||||
@@ -27,4 +32,16 @@ export interface CatalogRepository {
|
|||||||
addDeviceTemplate(template: Omit<DeviceTemplate, 'id' | 'custom'>): Promise<DeviceTemplate>
|
addDeviceTemplate(template: Omit<DeviceTemplate, 'id' | 'custom'>): Promise<DeviceTemplate>
|
||||||
updateDeviceTemplate(id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>): Promise<void>
|
updateDeviceTemplate(id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>): Promise<void>
|
||||||
removeDeviceTemplate(id: string): Promise<void>
|
removeDeviceTemplate(id: string): Promise<void>
|
||||||
|
|
||||||
|
/** Admin/Super-Admin direct edit of an already-public port/cable/device
|
||||||
|
* entry — same underlying write as approving a submission, minus the
|
||||||
|
* submission. */
|
||||||
|
adminUpdatePortType(id: string, patch: Partial<Omit<PortType, 'id' | 'custom'>>): Promise<void>
|
||||||
|
adminUpdateCableType(id: string, patch: Partial<Omit<CableType, 'id' | 'custom'>>): Promise<void>
|
||||||
|
adminUpdateDeviceTemplate(id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>): Promise<void>
|
||||||
|
/** Unpublishes a public entry (is_public -> false) rather than deleting
|
||||||
|
* it — organized-ideas.md §3's "public catalog entries are never hard-
|
||||||
|
* deleted, only hidden/unpublished". Existing diagrams that reference it
|
||||||
|
* by id are unaffected; it just stops being offered for new use. */
|
||||||
|
adminUnpublish(entityType: CatalogEntityType, id: string): Promise<void>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,10 @@
|
|||||||
import { v4 as uuid } from 'uuid'
|
import { v4 as uuid } from 'uuid'
|
||||||
import type { AdminSubmissionRepository, UsageImpact, UsageImpactSample } from './AdminSubmissionRepository'
|
import type { AdminSubmissionRepository, UsageImpact, UsageImpactSample } from './AdminSubmissionRepository'
|
||||||
|
import { CATALOG_TABLE_BY_ENTITY_TYPE } from './catalogRowMapping'
|
||||||
import type { CatalogSubmission } from './SubmissionRepository'
|
import type { CatalogSubmission } from './SubmissionRepository'
|
||||||
import { supabase } from './supabaseClient'
|
import { supabase } from './supabaseClient'
|
||||||
import { toSubmission, type SubmissionRow } from './submissionRowMapping'
|
import { toSubmission, type SubmissionRow } from './submissionRowMapping'
|
||||||
|
|
||||||
const TABLE_BY_ENTITY_TYPE: Record<CatalogSubmission['entityType'], string> = {
|
|
||||||
device_template: 'device_templates',
|
|
||||||
port_type: 'port_types',
|
|
||||||
cable_type: 'cable_types',
|
|
||||||
device_category: 'device_categories',
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProposedDeviceTemplatePort {
|
interface ProposedDeviceTemplatePort {
|
||||||
name: string
|
name: string
|
||||||
direction: string
|
direction: string
|
||||||
@@ -45,7 +39,7 @@ export class SupabaseAdminSubmissionRepository implements AdminSubmissionReposit
|
|||||||
// `ports` (device_template only) isn't a column on device_templates
|
// `ports` (device_template only) isn't a column on device_templates
|
||||||
// itself; pull it out and replace device_template_ports separately.
|
// itself; pull it out and replace device_template_ports separately.
|
||||||
const { ports, ...rowPatch } = submission.proposedData as Record<string, unknown> & { ports?: ProposedDeviceTemplatePort[] }
|
const { ports, ...rowPatch } = submission.proposedData as Record<string, unknown> & { ports?: ProposedDeviceTemplatePort[] }
|
||||||
const table = TABLE_BY_ENTITY_TYPE[submission.entityType]
|
const table = CATALOG_TABLE_BY_ENTITY_TYPE[submission.entityType]
|
||||||
const { error } = await supabase
|
const { error } = await supabase
|
||||||
.from(table)
|
.from(table)
|
||||||
.update({ ...rowPatch, is_public: true, owner_id: null })
|
.update({ ...rowPatch, is_public: true, owner_id: null })
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { FunctionsHttpError } from '@supabase/supabase-js'
|
||||||
|
import type { AdminUserRepository, AdminUserSummary, UserRole } from './AdminUserRepository'
|
||||||
|
import { supabase } from './supabaseClient'
|
||||||
|
|
||||||
|
interface UserRow {
|
||||||
|
id: string
|
||||||
|
username: string
|
||||||
|
email: string
|
||||||
|
role: UserRole
|
||||||
|
banned_until: string | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSummary(row: UserRow): AdminUserSummary {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
username: row.username,
|
||||||
|
email: row.email,
|
||||||
|
role: row.role,
|
||||||
|
bannedUntil: row.banned_until ?? undefined,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserAction = 'ban' | 'unban' | 'delete'
|
||||||
|
|
||||||
|
/** Backs the app with list_users_for_admin (read), a direct profiles.role
|
||||||
|
* update, and the admin-user-action Edge Function (ban/unban/delete). */
|
||||||
|
export class SupabaseAdminUserRepository implements AdminUserRepository {
|
||||||
|
async listUsers(): Promise<AdminUserSummary[]> {
|
||||||
|
const { data, error } = await supabase.rpc('list_users_for_admin')
|
||||||
|
if (error) {
|
||||||
|
console.error('Failed to list users from Supabase', error)
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
return ((data ?? []) as UserRow[]).map(toSummary)
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateRole(userId: string, role: UserRole): Promise<void> {
|
||||||
|
const { error } = await supabase.from('profiles').update({ role }).eq('id', userId)
|
||||||
|
if (error) console.error('Failed to update user role in Supabase', error)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async invokeUserAction(action: UserAction, userId: string): Promise<void> {
|
||||||
|
const { error } = await supabase.functions.invoke('admin-user-action', { body: { action, userId } })
|
||||||
|
if (!error) return
|
||||||
|
|
||||||
|
// The function returns its actual reason (e.g. "Only a Super Admin can
|
||||||
|
// manage user accounts.") in the JSON body on a non-2xx response —
|
||||||
|
// surface that instead of supabase-js's generic "Edge Function
|
||||||
|
// returned a non-2xx status code" wrapper.
|
||||||
|
if (error instanceof FunctionsHttpError) {
|
||||||
|
const body = await error.context.json().catch(() => null)
|
||||||
|
const message = typeof body?.error === 'string' ? body.error : error.message
|
||||||
|
console.error(`Failed to ${action} user`, message)
|
||||||
|
throw new Error(message)
|
||||||
|
}
|
||||||
|
console.error(`Failed to ${action} user`, error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
|
||||||
|
banUser(userId: string): Promise<void> {
|
||||||
|
return this.invokeUserAction('ban', userId)
|
||||||
|
}
|
||||||
|
|
||||||
|
unbanUser(userId: string): Promise<void> {
|
||||||
|
return this.invokeUserAction('unban', userId)
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteUser(userId: string): Promise<void> {
|
||||||
|
return this.invokeUserAction('delete', userId)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { v4 as uuid } from 'uuid'
|
import { v4 as uuid } from 'uuid'
|
||||||
import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, Port, PortType } from '../domain/types'
|
import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, Port, PortType } from '../domain/types'
|
||||||
import { cableTypeToRow, deviceTemplateToRow, portTypeToRow } from './catalogRowMapping'
|
import { CATALOG_TABLE_BY_ENTITY_TYPE, cableTypeToRow, deviceTemplateToRow, portTypeToRow } from './catalogRowMapping'
|
||||||
import type { CatalogRepository } from './CatalogRepository'
|
import type { CatalogRepository } from './CatalogRepository'
|
||||||
|
import type { CatalogEntityType } from './SubmissionRepository'
|
||||||
import { supabase } from './supabaseClient'
|
import { supabase } from './supabaseClient'
|
||||||
|
|
||||||
interface DeviceCategoryRow {
|
interface DeviceCategoryRow {
|
||||||
@@ -260,4 +261,28 @@ export class SupabaseCatalogRepository implements CatalogRepository {
|
|||||||
const { error } = await supabase.from('device_templates').delete().eq('id', id)
|
const { error } = await supabase.from('device_templates').delete().eq('id', id)
|
||||||
if (error) console.error('Failed to remove device template from Supabase', error)
|
if (error) console.error('Failed to remove device template from Supabase', error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The update* methods above never check ownership themselves — RLS does,
|
||||||
|
// server-side, based on the caller's identity — so an Admin/Super-Admin
|
||||||
|
// direct edit of a public entry is *exactly* the same write, just
|
||||||
|
// permitted by a different branch of the same policy (`is_admin()`
|
||||||
|
// instead of "owns it and it's still private"). These are aliases, not
|
||||||
|
// separate logic, so the two paths can't drift apart.
|
||||||
|
adminUpdatePortType(id: string, patch: Partial<Omit<PortType, 'id' | 'custom'>>): Promise<void> {
|
||||||
|
return this.updatePortType(id, patch)
|
||||||
|
}
|
||||||
|
|
||||||
|
adminUpdateCableType(id: string, patch: Partial<Omit<CableType, 'id' | 'custom'>>): Promise<void> {
|
||||||
|
return this.updateCableType(id, patch)
|
||||||
|
}
|
||||||
|
|
||||||
|
adminUpdateDeviceTemplate(id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>): Promise<void> {
|
||||||
|
return this.updateDeviceTemplate(id, patch)
|
||||||
|
}
|
||||||
|
|
||||||
|
async adminUnpublish(entityType: CatalogEntityType, id: string): Promise<void> {
|
||||||
|
const table = CATALOG_TABLE_BY_ENTITY_TYPE[entityType]
|
||||||
|
const { error } = await supabase.from(table).update({ is_public: false }).eq('id', id)
|
||||||
|
if (error) console.error('Failed to unpublish catalog entry in Supabase', error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { CatalogEntityType } from './SubmissionRepository'
|
||||||
import type { CableType, DeviceTemplate, PortType } from '../domain/types'
|
import type { CableType, DeviceTemplate, PortType } from '../domain/types'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -10,6 +11,16 @@ import type { CableType, DeviceTemplate, PortType } from '../domain/types'
|
|||||||
* step an Admin's approval action would otherwise have to duplicate.
|
* step an Admin's approval action would otherwise have to duplicate.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/** Which table backs each catalog entity type — shared by
|
||||||
|
* SupabaseAdminSubmissionRepository (approving into the right table) and
|
||||||
|
* SupabaseCatalogRepository (direct Admin unpublish). */
|
||||||
|
export const CATALOG_TABLE_BY_ENTITY_TYPE: Record<CatalogEntityType, string> = {
|
||||||
|
device_template: 'device_templates',
|
||||||
|
port_type: 'port_types',
|
||||||
|
cable_type: 'cable_types',
|
||||||
|
device_category: 'device_categories',
|
||||||
|
}
|
||||||
|
|
||||||
export function portTypeToRow(portType: Omit<PortType, 'id' | 'custom'>): Record<string, unknown> {
|
export function portTypeToRow(portType: Omit<PortType, 'id' | 'custom'>): Record<string, unknown> {
|
||||||
return {
|
return {
|
||||||
name: portType.name,
|
name: portType.name,
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { create } from 'zustand'
|
||||||
|
import type { AdminUserRepository, AdminUserSummary, UserRole } from '../data/AdminUserRepository'
|
||||||
|
import { SupabaseAdminUserRepository } from '../data/SupabaseAdminUserRepository'
|
||||||
|
|
||||||
|
const repository: AdminUserRepository = new SupabaseAdminUserRepository()
|
||||||
|
|
||||||
|
interface AdminUserStoreState {
|
||||||
|
users: AdminUserSummary[]
|
||||||
|
isLoaded: boolean
|
||||||
|
|
||||||
|
loadUsers: () => Promise<void>
|
||||||
|
updateRole: (userId: string, role: UserRole) => Promise<void>
|
||||||
|
banUser: (userId: string) => Promise<void>
|
||||||
|
unbanUser: (userId: string) => Promise<void>
|
||||||
|
deleteUser: (userId: string) => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAdminUserStore = create<AdminUserStoreState>((set) => ({
|
||||||
|
users: [],
|
||||||
|
isLoaded: false,
|
||||||
|
|
||||||
|
loadUsers: async () => {
|
||||||
|
const users = await repository.listUsers()
|
||||||
|
set({ users, isLoaded: true })
|
||||||
|
},
|
||||||
|
|
||||||
|
updateRole: async (userId, role) => {
|
||||||
|
await repository.updateRole(userId, role)
|
||||||
|
set((state) => ({ users: state.users.map((u) => (u.id === userId ? { ...u, role } : u)) }))
|
||||||
|
},
|
||||||
|
|
||||||
|
banUser: async (userId) => {
|
||||||
|
await repository.banUser(userId)
|
||||||
|
// Re-fetch rather than guessing bannedUntil client-side — the Edge
|
||||||
|
// Function is the one place that actually knows the real value.
|
||||||
|
const users = await repository.listUsers()
|
||||||
|
set({ users })
|
||||||
|
},
|
||||||
|
|
||||||
|
unbanUser: async (userId) => {
|
||||||
|
await repository.unbanUser(userId)
|
||||||
|
const users = await repository.listUsers()
|
||||||
|
set({ users })
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteUser: async (userId) => {
|
||||||
|
await repository.deleteUser(userId)
|
||||||
|
set((state) => ({ users: state.users.filter((u) => u.id !== userId) }))
|
||||||
|
},
|
||||||
|
}))
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { create } from 'zustand'
|
import { create } from 'zustand'
|
||||||
|
import type { UserRole } from '../data/AdminUserRepository'
|
||||||
import { supabase } from '../data/supabaseClient'
|
import { supabase } from '../data/supabaseClient'
|
||||||
|
|
||||||
export type UserRole = 'regular' | 'admin' | 'super_admin'
|
export type { UserRole }
|
||||||
|
|
||||||
interface AuthStoreState {
|
interface AuthStoreState {
|
||||||
userId: string | null
|
userId: string | null
|
||||||
@@ -10,9 +11,10 @@ interface AuthStoreState {
|
|||||||
isLoaded: boolean
|
isLoaded: boolean
|
||||||
|
|
||||||
/** One-time fetch of your own profile — nothing else in the app changes
|
/** One-time fetch of your own profile — nothing else in the app changes
|
||||||
* your own username or role while you're signed in (role changes are an
|
* your own username while you're signed in, and your own role changing
|
||||||
* Admin/Super-Admin-only action on someone else's account, see
|
* (a Super-Admin-only action on someone else's account, see
|
||||||
* organized-ideas.md §6, not yet built), so there's no need to keep this live. */
|
* organized-ideas.md §6) isn't something you'd do to yourself, so
|
||||||
|
* there's no need to keep this live. */
|
||||||
load: () => Promise<void>
|
load: () => Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { CableType, Catalog, DeviceTemplate, PortType } from '../domain/typ
|
|||||||
import type { CatalogRepository } from '../data/CatalogRepository'
|
import type { CatalogRepository } from '../data/CatalogRepository'
|
||||||
import { cableTypeToRow, deviceTemplateToRow, portTypeToRow } from '../data/catalogRowMapping'
|
import { cableTypeToRow, deviceTemplateToRow, portTypeToRow } from '../data/catalogRowMapping'
|
||||||
import { SupabaseCatalogRepository } from '../data/SupabaseCatalogRepository'
|
import { SupabaseCatalogRepository } from '../data/SupabaseCatalogRepository'
|
||||||
|
import type { CatalogEntityType } from '../data/SubmissionRepository'
|
||||||
import { useSubmissionStore } from './submissionStore'
|
import { useSubmissionStore } from './submissionStore'
|
||||||
|
|
||||||
const repository: CatalogRepository = new SupabaseCatalogRepository()
|
const repository: CatalogRepository = new SupabaseCatalogRepository()
|
||||||
@@ -51,6 +52,16 @@ interface CatalogStoreState {
|
|||||||
|
|
||||||
hidePublicDeviceTemplate: (id: string) => void
|
hidePublicDeviceTemplate: (id: string) => void
|
||||||
restorePublicDeviceTemplate: (id: string) => void
|
restorePublicDeviceTemplate: (id: string) => void
|
||||||
|
|
||||||
|
/** Admin/Super-Admin direct edit of an already-public entry, per
|
||||||
|
* organized-ideas.md §6 — bypasses the submission/review workflow
|
||||||
|
* entirely (RLS's is_admin() clause is what actually permits it). */
|
||||||
|
adminUpdatePortType: (id: string, patch: Partial<Omit<PortType, 'id' | 'custom'>>) => Promise<void>
|
||||||
|
adminUpdateCableType: (id: string, patch: Partial<Omit<CableType, 'id' | 'custom'>>) => Promise<void>
|
||||||
|
adminUpdateDeviceTemplate: (id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>) => Promise<void>
|
||||||
|
/** Unpublishes (is_public -> false) rather than deletes — see
|
||||||
|
* CatalogRepository.adminUnpublish. */
|
||||||
|
adminUnpublish: (entityType: CatalogEntityType, id: string) => Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useCatalogStore = create<CatalogStoreState>((set, get) => ({
|
export const useCatalogStore = create<CatalogStoreState>((set, get) => ({
|
||||||
@@ -140,4 +151,31 @@ export const useCatalogStore = create<CatalogStoreState>((set, get) => ({
|
|||||||
saveHiddenPublicIds(next)
|
saveHiddenPublicIds(next)
|
||||||
set({ hiddenPublicDeviceTemplateIds: next })
|
set({ hiddenPublicDeviceTemplateIds: next })
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Re-fetch the whole catalog after each of these rather than patching
|
||||||
|
// locally — device_template edits also touch device_template_ports, and
|
||||||
|
// unpublish changes which rows even show up (custom flips true for the
|
||||||
|
// Admin who did it, since is_admin() is the only thing still granting
|
||||||
|
// them visibility — see adminUnpublish's own comment). Simplest correct
|
||||||
|
// thing, and Admin actions here are infrequent enough that the extra
|
||||||
|
// round trip doesn't matter.
|
||||||
|
adminUpdatePortType: async (id, patch) => {
|
||||||
|
await repository.adminUpdatePortType(id, patch)
|
||||||
|
await get().loadCatalog()
|
||||||
|
},
|
||||||
|
|
||||||
|
adminUpdateCableType: async (id, patch) => {
|
||||||
|
await repository.adminUpdateCableType(id, patch)
|
||||||
|
await get().loadCatalog()
|
||||||
|
},
|
||||||
|
|
||||||
|
adminUpdateDeviceTemplate: async (id, patch) => {
|
||||||
|
await repository.adminUpdateDeviceTemplate(id, patch)
|
||||||
|
await get().loadCatalog()
|
||||||
|
},
|
||||||
|
|
||||||
|
adminUnpublish: async (entityType, id) => {
|
||||||
|
await repository.adminUnpublish(entityType, id)
|
||||||
|
await get().loadCatalog()
|
||||||
|
},
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -431,3 +431,18 @@ enabled = true
|
|||||||
# declarative_schema_path = "./schemas"
|
# declarative_schema_path = "./schemas"
|
||||||
# JSON string passed through to pg-delta SQL formatting.
|
# JSON string passed through to pg-delta SQL formatting.
|
||||||
# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}"
|
# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}"
|
||||||
|
|
||||||
|
[functions.admin-user-action]
|
||||||
|
enabled = true
|
||||||
|
# This function expects a real signed-in user's JWT (auth: 'user' mode in
|
||||||
|
# index.ts already verifies it via project JWKS) — verify_jwt = true adds a
|
||||||
|
# cheap gateway-level rejection of missing/malformed tokens before the
|
||||||
|
# function even runs, on top of that.
|
||||||
|
verify_jwt = true
|
||||||
|
import_map = "./functions/admin-user-action/deno.json"
|
||||||
|
# Uncomment to specify a custom file path to the entrypoint.
|
||||||
|
# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx
|
||||||
|
entrypoint = "./functions/admin-user-action/index.ts"
|
||||||
|
# Specifies static files to be bundled with the function. Supports glob patterns.
|
||||||
|
# For example, if you want to serve static HTML pages in your function:
|
||||||
|
# static_files = [ "./functions/admin-user-action/*.html" ]
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Configuration for private npm package dependencies
|
||||||
|
# For more information on using private registries with Edge Functions, see:
|
||||||
|
# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"imports": {
|
||||||
|
"@supabase/functions-js": "jsr:@supabase/functions-js@^2",
|
||||||
|
"@supabase/server": "npm:@supabase/server@^1"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// Ban/unban/delete a user account — organized-ideas.md §6, Super-Admin only.
|
||||||
|
//
|
||||||
|
// This has to be an Edge Function rather than a Postgres function (unlike
|
||||||
|
// list_users_for_admin or the other privileged functions in this codebase):
|
||||||
|
// touching auth.users needs Supabase Auth's Admin API (the stable,
|
||||||
|
// documented interface for account mutations), not a direct SQL write to
|
||||||
|
// a schema Supabase manages internally and doesn't guarantee stable
|
||||||
|
// across upgrades. Ban is reversible (banned_until, no data touched);
|
||||||
|
// delete cascades to profiles/diagrams via their existing FKs.
|
||||||
|
//
|
||||||
|
// To invoke locally (after `supabase start`), with a real user's access
|
||||||
|
// token in place of ACCESS_TOKEN:
|
||||||
|
// curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/admin-user-action' \
|
||||||
|
// --header 'apiKey: <anon key from `supabase status`>' \
|
||||||
|
// --header 'Authorization: Bearer ACCESS_TOKEN' \
|
||||||
|
// --header 'Content-Type: application/json' \
|
||||||
|
// --data '{"action":"ban","userId":"..."}'
|
||||||
|
|
||||||
|
import "@supabase/functions-js/edge-runtime.d.ts";
|
||||||
|
import { withSupabase } from "@supabase/server";
|
||||||
|
|
||||||
|
type Action = "ban" | "unban" | "delete";
|
||||||
|
|
||||||
|
interface RequestBody {
|
||||||
|
action: Action;
|
||||||
|
userId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const VALID_ACTIONS: Action[] = ["ban", "unban", "delete"];
|
||||||
|
|
||||||
|
// ~100 years — Supabase Auth's own documented idiom for "indefinite ban"
|
||||||
|
// (there's no literal "forever" value); "none" is the matching unban value.
|
||||||
|
const PERMANENT_BAN_DURATION = "876000h";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
|
||||||
|
const callerId = ctx.userClaims!.id;
|
||||||
|
|
||||||
|
// Confirm the caller is a Super Admin by reading their own profile
|
||||||
|
// through the user-scoped (RLS-respecting) client — this leans on the
|
||||||
|
// same "read your own row" policy every other profile read in the app
|
||||||
|
// uses, rather than trusting anything in the JWT itself (its `role`
|
||||||
|
// claim is just "authenticated", not this app's role column).
|
||||||
|
const { data: callerProfile, error: profileError } = await ctx.supabase
|
||||||
|
.from("profiles")
|
||||||
|
.select("role")
|
||||||
|
.eq("id", callerId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (profileError || callerProfile?.role !== "super_admin") {
|
||||||
|
return Response.json({ error: "Only a Super Admin can manage user accounts." }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: RequestBody;
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return Response.json({ error: "Invalid request body." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { action, userId } = body;
|
||||||
|
if (typeof userId !== "string" || !userId || !VALID_ACTIONS.includes(action)) {
|
||||||
|
return Response.json({ error: "Request must include a valid action and userId." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userId === callerId) {
|
||||||
|
return Response.json({ error: "You cannot perform this action on your own account." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action === "ban") {
|
||||||
|
const { error } = await ctx.supabaseAdmin.auth.admin.updateUserById(userId, {
|
||||||
|
ban_duration: PERMANENT_BAN_DURATION,
|
||||||
|
});
|
||||||
|
if (error) return Response.json({ error: error.message }, { status: 500 });
|
||||||
|
} else if (action === "unban") {
|
||||||
|
const { error } = await ctx.supabaseAdmin.auth.admin.updateUserById(userId, { ban_duration: "none" });
|
||||||
|
if (error) return Response.json({ error: error.message }, { status: 500 });
|
||||||
|
} else {
|
||||||
|
// Cascades to profiles (and from there, diagrams/owned catalog
|
||||||
|
// entries) via their existing `on delete cascade` foreign keys —
|
||||||
|
// the frontend confirmation for this action says so explicitly,
|
||||||
|
// since it's the one irreversible option here.
|
||||||
|
const { error } = await ctx.supabaseAdmin.auth.admin.deleteUser(userId);
|
||||||
|
if (error) return Response.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json({ success: true });
|
||||||
|
}),
|
||||||
|
};
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
-- Super-Admin user management (organized-ideas.md §6): "CRUD user accounts"
|
||||||
|
-- starts with being able to see them at all. auth.users isn't exposed
|
||||||
|
-- through PostgREST (by design — Supabase doesn't expose the `auth` schema
|
||||||
|
-- to the API), so this read-only, Super-Admin-gated function is the only
|
||||||
|
-- way the app can list users alongside their profile/ban status. The
|
||||||
|
-- mutations themselves (ban/unban/delete) go through a new Edge Function
|
||||||
|
-- instead of a SQL function here — those specifically need Supabase Auth's
|
||||||
|
-- Admin API (auth.admin.updateUserById/deleteUser), the stable, documented
|
||||||
|
-- interface for touching auth.users, rather than writing to that schema's
|
||||||
|
-- tables directly (undocumented, not guaranteed stable across upgrades).
|
||||||
|
|
||||||
|
create or replace function public.list_users_for_admin()
|
||||||
|
returns table(id uuid, username text, email text, role text, banned_until timestamptz, created_at timestamptz)
|
||||||
|
language plpgsql
|
||||||
|
stable
|
||||||
|
security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
begin
|
||||||
|
if not public.is_super_admin() then
|
||||||
|
raise exception 'insufficient_privilege' using errcode = '42501';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
return query
|
||||||
|
select p.id, p.username, u.email::text, p.role, u.banned_until, p.created_at
|
||||||
|
from public.profiles p
|
||||||
|
join auth.users u on u.id = p.id
|
||||||
|
order by p.created_at desc;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
+42
-1
@@ -25,7 +25,7 @@ begin;
|
|||||||
|
|
||||||
create extension if not exists pgtap with schema extensions;
|
create extension if not exists pgtap with schema extensions;
|
||||||
|
|
||||||
select plan(38);
|
select plan(43);
|
||||||
|
|
||||||
-- ----------------------------------------------------------------------
|
-- ----------------------------------------------------------------------
|
||||||
-- Fixtures (as postgres — RLS does not apply)
|
-- Fixtures (as postgres — RLS does not apply)
|
||||||
@@ -386,6 +386,47 @@ select is(
|
|||||||
'carol (admin) can look up the submitter''s username for a submission she can review'
|
'carol (admin) can look up the submitter''s username for a submission she can review'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
-- Admin user listing (organized-ideas.md §6: "CRUD user accounts" is
|
||||||
|
-- Super-Admin-only — even a regular Admin gets 42501 here, unlike the
|
||||||
|
-- Admin-gated functions above).
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
|
||||||
|
|
||||||
|
select throws_ok(
|
||||||
|
$$ select * from public.list_users_for_admin() $$,
|
||||||
|
'42501'::char(5), null,
|
||||||
|
'bob (regular user) cannot list users'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '33333333-3333-3333-3333-333333333333', true);
|
||||||
|
|
||||||
|
select throws_ok(
|
||||||
|
$$ select * from public.list_users_for_admin() $$,
|
||||||
|
'42501'::char(5), null,
|
||||||
|
'carol (admin, not super admin) cannot list users'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '44444444-4444-4444-4444-444444444444', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ select * from public.list_users_for_admin() $$,
|
||||||
|
'dave (super admin) can list users'
|
||||||
|
);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select role from public.list_users_for_admin() where username = 'alice'),
|
||||||
|
'admin',
|
||||||
|
'the listing reflects alice''s current role (promoted earlier in this test run)'
|
||||||
|
);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select email from public.list_users_for_admin() where username = 'alice'),
|
||||||
|
'alice@example.com',
|
||||||
|
'the listing includes email, only readable via this Super-Admin-gated function (not directly through PostgREST)'
|
||||||
|
);
|
||||||
|
|
||||||
select * from finish();
|
select * from finish();
|
||||||
|
|
||||||
rollback;
|
rollback;
|
||||||
|
|||||||
Reference in New Issue
Block a user