feat: allow admin removing members from a network

This commit is contained in:
talksik
2026-04-16 15:01:04 -07:00
parent c64d04e0c5
commit 8785187ccc
9 changed files with 190 additions and 85 deletions
+1 -1
View File
@@ -147,7 +147,7 @@ func main() {
mux.Handle("GET /networks", withAuth(h.ListNetworks)) mux.Handle("GET /networks", withAuth(h.ListNetworks))
mux.Handle("GET /networks/{id}", withAuth(h.GetNetwork)) mux.Handle("GET /networks/{id}", withAuth(h.GetNetwork))
mux.Handle("POST /networks/{id}/members", withAuth(h.AddMembersToNetwork)) mux.Handle("POST /networks/{id}/members", withAuth(h.AddMembersToNetwork))
// mux.Handle("DELETE /networks/{id}/members/{humanId}", withAuth(h.RemoveMemberFromNetwork)) mux.Handle("DELETE /networks/{id}/members/{humanId}", withAuth(h.RemoveMemberFromNetwork))
// Billing (network admin only; admin check happens inside each handler) // Billing (network admin only; admin check happens inside each handler)
mux.Handle("GET /networks/{id}/billing", withAuth(h.GetNetworkBilling)) mux.Handle("GET /networks/{id}/billing", withAuth(h.GetNetworkBilling))
+2 -2
View File
@@ -37,8 +37,8 @@ func main() {
pusherRedis := internal.ConnectAndTestRedis(db.RedisDBPusher) pusherRedis := internal.ConnectAndTestRedis(db.RedisDBPusher)
// Services // Services
authSvc := auth.NewAuthService(authRedis, nil, nil) // nil aeroSvc / fbAuth — pusher only calls GetSession authSvc := auth.NewAuthService(authRedis, nil, nil) // nil aeroSvc / fbAuth — pusher only calls GetSession
networkSvc := network.NewService(db.Pool(), nil, billing.Noop(), nil) // nil aeroSvc / noop billing / nil firestore — pusher never mutates membership networkSvc := network.NewService(db.Pool(), nil, billing.Noop(), nil) // nil aeroSvc / noop billing / nil firestore — pusher never mutates membership
// Pod identity (use hostname in k8s, which is the pod name) // Pod identity (use hostname in k8s, which is the pod name)
podID, err := os.Hostname() podID, err := os.Hostname()
+10 -16
View File
@@ -546,34 +546,28 @@ func (h *Handler) AddMembersToNetwork(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(resp) json.NewEncoder(w).Encode(resp)
} }
// RemoveMemberFromNetwork removes a member from a network // RemoveMemberFromNetwork removes a member from a network. Admin-only.
// Admins cannot remove themselves — doing so would leave networks.admin_human_id
// dangling. Removal of a non-member is a no-op (204).
func (h *Handler) RemoveMemberFromNetwork(w http.ResponseWriter, r *http.Request) { func (h *Handler) RemoveMemberFromNetwork(w http.ResponseWriter, r *http.Request) {
humanId, ok := middleware.HumanIdFromContext(r.Context()) net, _, ok := h.loadNetworkForAdmin(w, r)
if !ok { if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return return
} }
networkID := r.PathValue("id")
memberHumanId := r.PathValue("humanId") memberHumanId := r.PathValue("humanId")
if networkID == "" || memberHumanId == "" { if memberHumanId == "" {
http.Error(w, "network id and member humanId are required", http.StatusBadRequest) http.Error(w, "member humanId is required", http.StatusBadRequest)
return return
} }
isMember, err := h.networkSvc.IsMember(r.Context(), networkID, humanId) if memberHumanId == net.AdminHumanId {
if err != nil { http.Error(w, "admin cannot remove themselves", http.StatusConflict)
slog.Error("failed to check network membership", "error", err, "network_id", networkID, "humanId", humanId)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if !isMember {
http.Error(w, "access denied", http.StatusForbidden)
return return
} }
if err := h.networkSvc.RemoveMember(r.Context(), networkID, memberHumanId); err != nil { if err := h.networkSvc.RemoveMember(r.Context(), net.ID, memberHumanId); err != nil {
slog.Error("failed to remove member from network", "error", err, "network_id", networkID, "memberHumanId", memberHumanId) slog.Error("failed to remove member from network", "error", err, "network_id", net.ID, "memberHumanId", memberHumanId)
http.Error(w, "internal server error", http.StatusInternalServerError) http.Error(w, "internal server error", http.StatusInternalServerError)
return return
} }
+2 -2
View File
@@ -192,10 +192,10 @@ class ApiClient {
); );
} }
async removeMember(networkId: string, email: string): Promise<void> { async removeMember(networkId: string, humanId: string): Promise<void> {
await this.requestVoid( await this.requestVoid(
"DELETE", "DELETE",
`/networks/${networkId}/members/${email}`, `/networks/${networkId}/members/${humanId}`,
); );
} }
@@ -0,0 +1,72 @@
import { useEffect } from "react";
import { createPortal } from "react-dom";
import { Button } from "@/components/ui/button";
interface ConfirmDestructiveOverlayProps {
title: string;
description: React.ReactNode;
confirmLabel: string;
pendingLabel?: string;
isPending: boolean;
onConfirm: () => void;
onClose: () => void;
}
export function ConfirmDestructiveOverlay({
title,
description,
confirmLabel,
pendingLabel = "Working…",
isPending,
onConfirm,
onClose,
}: ConfirmDestructiveOverlayProps) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
onClose();
}
};
window.addEventListener("keydown", handler, { capture: true });
return () => window.removeEventListener("keydown", handler, { capture: true });
}, [onClose]);
return createPortal(
<div className="fixed inset-0 z-[100]">
<div
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={onClose}
/>
<div className="absolute left-1/2 top-1/2 w-full max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-white/10 bg-white/5 p-6 shadow-2xl backdrop-blur-xl">
<div className="mb-3 flex items-center justify-between">
<h2 className="text-sm font-semibold text-white/70">{title}</h2>
<span className="text-xs text-white/30">
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
Esc
</kbd>{" "}
to close
</span>
</div>
<div className="text-sm text-white/60">{description}</div>
<div className="mt-5 flex items-center justify-end gap-2">
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
Cancel
</Button>
<Button
variant="destructive"
size="sm"
onClick={onConfirm}
disabled={isPending}
>
{isPending ? pendingLabel : confirmLabel}
</Button>
</div>
</div>
</div>,
document.body,
);
}
+1 -1
View File
@@ -19,7 +19,7 @@ import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area"; import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { useNetworks } from "@/hooks/use-networks"; import { useNetworks } from "@/hooks/use-networks";
import { useMyInvitations, useAcceptInvitation } from "@/hooks/use-invitations"; import { useMyInvitations, useAcceptInvitation } from "@/hooks/use-member-management";
import { apiClient } from "@/api/client"; import { apiClient } from "@/api/client";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import type { Network, Invitation } from "@/api/types"; import type { Network, Invitation } from "@/api/types";
+78 -13
View File
@@ -15,12 +15,22 @@ import {
useNetworkInvitations, useNetworkInvitations,
useInviteMembers, useInviteMembers,
useRevokeInvitation, useRevokeInvitation,
} from "@/hooks/use-invitations"; useRemoveMember,
} from "@/hooks/use-member-management";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore } from "@/stores/auth-store";
import { BillingSection } from "@/features/network-billing"; import { BillingSection } from "@/features/network-billing";
import { ConfirmDestructiveOverlay } from "@/components/confirm-destructive-overlay";
import type { Human } from "@/api/types"; import type { Human } from "@/api/types";
function MemberRow({ human, isAdmin }: { human: Human; isAdmin: boolean }) { function MemberRow({
human,
isAdmin,
onRemove,
}: {
human: Human;
isAdmin: boolean;
onRemove?: () => void;
}) {
const initials = human.email_prefix.slice(0, 2).toUpperCase(); const initials = human.email_prefix.slice(0, 2).toUpperCase();
return ( return (
@@ -40,6 +50,17 @@ function MemberRow({ human, isAdmin }: { human: Human; isAdmin: boolean }) {
Admin Admin
</Badge> </Badge>
)} )}
{onRemove && (
<Button
variant="ghost"
size="icon-sm"
onClick={onRemove}
className="text-muted-foreground hover:text-destructive shrink-0"
aria-label={`Remove ${human.email}`}
>
<X className="size-3.5" />
</Button>
)}
</div> </div>
); );
} }
@@ -170,6 +191,8 @@ export default function NetworkSettingsPage() {
const { data: invitations } = useNetworkInvitations(networkId!); const { data: invitations } = useNetworkInvitations(networkId!);
const currentUser = useAuthStore((s) => s.user); const currentUser = useAuthStore((s) => s.user);
const isAdmin = currentUser?.id === network?.admin_human.id; const isAdmin = currentUser?.id === network?.admin_human.id;
const [memberToRemove, setMemberToRemove] = useState<Human | null>(null);
const removeMember = useRemoveMember(networkId!);
const billingRef = useRef<HTMLDivElement>(null); const billingRef = useRef<HTMLDivElement>(null);
@@ -228,17 +251,23 @@ export default function NetworkSettingsPage() {
} }
/> />
<Separator /> <Separator />
{network?.humans.map((human, index) => ( {network?.humans.map((human, index) => {
<div key={human.id}> const isRowAdmin = human.id === network.admin_human.id;
<MemberRow const canRemove =
human={human} isAdmin && !isRowAdmin && human.id !== currentUser?.id;
isAdmin={human.id === network.admin_human.id} return (
/> <div key={human.id}>
{index < network.humans.length - 1 && ( <MemberRow
<Separator className="mx-4" /> human={human}
)} isAdmin={isRowAdmin}
</div> onRemove={canRemove ? () => setMemberToRemove(human) : undefined}
))} />
{index < network.humans.length - 1 && (
<Separator className="mx-4" />
)}
</div>
);
})}
</Section> </Section>
{isAdmin && network && ( {isAdmin && network && (
@@ -299,6 +328,42 @@ export default function NetworkSettingsPage() {
<div className="h-6" /> <div className="h-6" />
</ScrollArea> </ScrollArea>
{memberToRemove && (
<ConfirmDestructiveOverlay
title={`Remove ${memberToRemove.email_prefix}?`}
description={
<ul className="list-disc space-y-1 pl-4">
<li>
They'll lose access to this network's streams and files within
seconds.
</li>
<li>Any content they posted stays in the network.</li>
<li>
If they're in a live huddle, they may remain until the call ends.
</li>
</ul>
}
confirmLabel="Remove"
pendingLabel="Removing…"
isPending={removeMember.isPending}
onConfirm={() => {
const target = memberToRemove;
removeMember.mutate(target.id, {
onSuccess: () => {
toast.success(`Removed ${target.email}`);
setMemberToRemove(null);
},
onError: (err) => {
toast.error(err.message || "Failed to remove member");
},
});
}}
onClose={() => {
if (!removeMember.isPending) setMemberToRemove(null);
}}
/>
)}
</div> </div>
); );
} }
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from "react"; import { useCallback, useState } from "react";
import { createPortal } from "react-dom";
import { toast } from "sonner"; import { toast } from "sonner";
import { Button } from "@/components/ui/button"; import { ConfirmDestructiveOverlay } from "@/components/confirm-destructive-overlay";
import { softDeleteParticle } from "@/lib/firestore-particles"; import { softDeleteParticle } from "@/lib/firestore-particles";
import { particlePath, toFirestoreDocPath } from "@/lib/particle-path"; import { particlePath, toFirestoreDocPath } from "@/lib/particle-path";
import type { Particle } from "@/api/types"; import type { Particle } from "@/api/types";
@@ -40,55 +39,20 @@ export function DeleteParticleOverlay({
} }
}, [deleting, networkId, onClose, particle.id, streamId, userId]); }, [deleting, networkId, onClose, particle.id, streamId, userId]);
useEffect(() => { return (
const handler = (e: KeyboardEvent) => { <ConfirmDestructiveOverlay
if (e.key === "Escape") { title="Delete this particle?"
e.preventDefault(); description={
e.stopPropagation(); <p>
onClose();
}
};
window.addEventListener("keydown", handler, { capture: true });
return () => window.removeEventListener("keydown", handler, { capture: true });
}, [onClose]);
return createPortal(
<div className="fixed inset-0 z-[100]">
<div
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={onClose}
/>
<div className="absolute left-1/2 top-1/2 w-full max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-white/10 bg-white/5 p-6 shadow-2xl backdrop-blur-xl">
<div className="mb-3 flex items-center justify-between">
<h2 className="text-sm font-semibold text-white/70">Delete this particle?</h2>
<span className="text-xs text-white/30">
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
Esc
</kbd>{" "}
to close
</span>
</div>
<p className="text-sm text-white/60">
This cannot be undone. Other viewers will see a "This particle was This cannot be undone. Other viewers will see a "This particle was
deleted" message in its place. deleted" message in its place.
</p> </p>
}
<div className="mt-5 flex items-center justify-end gap-2"> confirmLabel="Delete"
<Button variant="ghost" size="sm" onClick={onClose} disabled={deleting}> pendingLabel="Deleting…"
Cancel isPending={deleting}
</Button> onConfirm={handleDelete}
<Button onClose={onClose}
variant="destructive" />
size="sm"
onClick={handleDelete}
disabled={deleting}
>
{deleting ? "Deleting…" : "Delete"}
</Button>
</div>
</div>
</div>,
document.body,
); );
} }
@@ -50,3 +50,13 @@ export function useRevokeInvitation(networkId: string) {
}, },
}); });
} }
export function useRemoveMember(networkId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (humanId: string) => apiClient.removeMember(networkId, humanId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["networks"] });
},
});
}