Files
Homelab-manager/web/src/components/AuthentikGroupList.tsx
T
bobbanandClaude Sonnet 5.5 e4cd01e9ba Delete Authentik groups
Each group in Apps → Authentik → Users and groups gets a Delete button: the
group's name has to be typed, and the server checks it against the group as
Authentik has it now. A group that makes its members administrators is
refused (deleted in Authentik). A group that decides roles in this app may be
deleted after a warning, and the audit log records its member count and that
it decided a role. Members stay, just not in the group.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 04:00:47 +01:00

279 lines
13 KiB
TypeScript

import { useEffect, useState, type FormEvent } from "react";
import { api, type AuthentikGroupDetail, type AuthentikGroupPerson, type AuthentikInfo } from "../api/client";
import { ErrorNotice, SuccessNotice } from "./Notice";
import { confirmDialog, promptDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
function EditGroup({ g, people, self, busy, onSave, onCancel }: { g: AuthentikGroupDetail; people: AuthentikGroupPerson[]; self: number | null; busy: boolean; onSave: (name: string, add: number[], remove: number[]) => void; onCancel: () => void }) {
const [name, setName] = useState(g.name);
const [members, setMembers] = useState<number[]>(g.members ?? []);
const [filter, setFilter] = useState("");
const canEditMembers = g.members !== null;
const shown = people.filter((p) => !filter.trim() || `${p.username} ${p.name}`.toLowerCase().includes(filter.trim().toLowerCase()));
// Members who are not in the list of people — service accounts, or beyond the first 200 — are not shown and are never taken out from here.
const hidden = (g.members ?? []).filter((m) => !people.some((p) => p.pk === m)).length;
const toggle = (pk: number) => setMembers((cur) => (cur.includes(pk) ? cur.filter((x) => x !== pk) : [...cur, pk]));
function submit(e: FormEvent) {
e.preventDefault();
const was = g.members ?? [];
const add = canEditMembers ? members.filter((m) => !was.includes(m)) : [];
const remove = canEditMembers ? was.filter((m) => !members.includes(m) && people.some((p) => p.pk === m)) : [];
if (name.trim() === g.name && add.length === 0 && remove.length === 0) return onCancel();
onSave(name.trim(), add, remove);
}
return (
<form onSubmit={submit} className="p-2">
{g.decidesRole && (
<div className="alert alert-warning py-2 small">
This group decides who is {g.decidesRole === "admin" ? "an administrator" : "an operator"} <em>here</em> (Settings → Sign-in). Renaming it, or changing who is in it, changes that at their next sign-in.
</div>
)}
{g.admin && <div className="text-secondary small mb-2">Members of this group are administrators of Authentik. Whether a group is one is changed in Authentik, not here.</div>}
<label className="form-label" htmlFor={`ak-group-name-${g.id}`}>
Name
</label>
<input id={`ak-group-name-${g.id}`} className="form-control form-control-sm mb-3" style={{ maxWidth: 360 }} required maxLength={200} autoComplete="off" value={name} onChange={(e) => setName(e.target.value)} />
<div className="form-label">Members</div>
{!canEditMembers ? (
<div className="text-secondary small mb-3">Authentik did not say who is in this group, so only its name can be changed here.</div>
) : (
<>
<input className="form-control form-control-sm mb-2" style={{ maxWidth: 360 }} placeholder="Find a user" aria-label="Find a user" value={filter} onChange={(e) => setFilter(e.target.value)} />
<div className="border rounded p-2 mb-1" style={{ maxHeight: 240, overflowY: "auto" }}>
{shown.length === 0 && <div className="text-secondary small">No user matches.</div>}
{shown.map((p) => (
<label key={p.pk} className="form-check">
<input type="checkbox" className="form-check-input" checked={members.includes(p.pk)} disabled={p.pk === self} onChange={() => toggle(p.pk)} />
<span className="form-check-label">
{p.username}
{p.name !== p.username && <span className="text-secondary"> — {p.name}</span>}
{!p.active && <span className="badge bg-secondary-lt text-secondary ms-2">off</span>}
{p.pk === self && <span className="text-secondary small ms-2">this token&rsquo;s account — looked after in Authentik</span>}
</span>
</label>
))}
</div>
{hidden > 0 && <div className="text-secondary small mb-2">{hidden} member{hidden === 1 ? " is" : "s are"} not shown (service accounts, or beyond the first 200 users) and are left as they are.</div>}
</>
)}
<div className="d-flex gap-2 mt-2">
<button type="submit" className="btn btn-sm btn-primary" disabled={busy}>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" className="btn btn-sm btn-link text-secondary" onClick={onCancel} disabled={busy}>
Cancel
</button>
</div>
</form>
);
}
/**
* The groups of an Authentik, read when the tab opens, for an administrator to make, rename, delete and to put users in and take them out of. Whether a group makes its members administrators is shown, not changed — and a group
* made here never does. A group that
* decides somebody's role in this app says so, and asks before it is changed.
*/
export default function AuthentikGroupList({ a }: { a: AuthentikInfo }) {
const [groups, setGroups] = useState<AuthentikGroupDetail[] | null>(null);
const [people, setPeople] = useState<AuthentikGroupPerson[]>([]);
const [self, setSelf] = useState<number | null>(null);
const [editing, setEditing] = useState<string | null>(null);
const [busy, setBusy] = useState<string | "list" | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
const [newName, setNewName] = useState("");
// Read as the tab opens, like the users. If that fails, the button below tries again.
useEffect(() => {
if (a.canCreateUsers) void load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [a.id, a.canCreateUsers]);
if (!a.canCreateUsers) return null;
async function create(e: FormEvent) {
e.preventDefault();
if (busy !== null) return;
setBusy("new");
setError(null);
setNotice(null);
try {
const { group } = await api.authentik.createGroup(a.id, newName.trim());
setCreating(false);
setNewName("");
setNotice(
`Made "${group.name}", with no members.${group.decidesRole ? ` Its name decides who is ${group.decidesRole === "admin" ? "an administrator" : "an operator"} here (Settings → Sign-in): whoever is put in it gets that role at their next sign-in.` : ""}`,
);
if (groups !== null) await load();
else setBusy(null);
} catch (err) {
setError(readableError(err));
setBusy(null);
}
}
async function load() {
setBusy("list");
setError(null);
try {
const r = await api.authentik.groupDetails(a.id);
setGroups(r.groups);
setPeople(r.people);
setSelf(r.self);
} catch (err) {
setError(readableError(err));
} finally {
setBusy(null);
}
}
async function removeGroup(g: AuthentikGroupDetail) {
const members = g.members === null ? "" : g.members.length === 0 ? " It has no members." : ` Its ${g.members.length} member${g.members.length === 1 ? "" : "s"} stay${g.members.length === 1 ? "s" : ""}, just not in it.`;
const roles = g.decidesRole ? ` It decides who is ${g.decidesRole === "admin" ? "an administrator" : "an operator"} in this app (Settings → Sign-in): people in it lose that role here at their next sign-in.` : "";
const typed = await promptDialog({
title: "Delete group",
message: `This deletes the group "${g.name}" in ${a.name} for good. It cannot be undone.${members}${roles} Type the name of the group to confirm.`,
label: "Group name",
confirmLabel: "Delete",
required: true,
});
if (typed === null) return;
if (typed.trim() !== g.name) {
setError("That is not the name of the group, so nothing was deleted.");
return;
}
setBusy(g.id);
setError(null);
setNotice(null);
try {
await api.authentik.deleteGroup(a.id, g.id, g.name);
setNotice(`Deleted "${g.name}".`);
await load();
} catch (err) {
setError(readableError(err));
setBusy(null);
}
}
async function save(g: AuthentikGroupDetail, name: string, add: number[], remove: number[]) {
if (g.decidesRole) {
const ok = await confirmDialog({
title: "Change a group that decides roles",
message: `"${g.name}" decides who is ${g.decidesRole === "admin" ? "an administrator" : "an operator"} in this app. Changing its name or its members changes people's roles here at their next sign-in. Go on?`,
confirmLabel: "Save",
danger: true,
});
if (!ok) return;
}
setBusy(g.id);
setError(null);
setNotice(null);
try {
const r = await api.authentik.updateGroup(a.id, g.id, { name: name !== g.name ? name : undefined, membersAdd: add, membersRemove: remove });
setEditing(null);
setNotice(r.changed.length === 0 ? "Nothing was different." : `Saved "${name}"${r.added + r.removed > 0 ? ` — ${r.added} put in, ${r.removed} taken out` : ""}.`);
await load();
} catch (err) {
setError(readableError(err));
setBusy(null);
}
}
return (
<div className="mt-3">
<h4>Groups</h4>
<ErrorNotice error={error} />
<SuccessNotice notice={notice} />
{creating ? (
<form onSubmit={create} className="card card-sm mb-2">
<div className="card-body">
<label className="form-label" htmlFor={`ak-new-group-${a.id}`}>
Name of the new group
</label>
<input id={`ak-new-group-${a.id}`} className="form-control form-control-sm mb-2" style={{ maxWidth: 360 }} required maxLength={200} autoComplete="off" autoFocus value={newName} onChange={(e) => setNewName(e.target.value)} />
<div className="text-secondary small mb-2">It starts with no members — put them in with Edit — and it does not make its members administrators of Authentik; that is decided in Authentik.</div>
<div className="d-flex gap-2">
<button type="submit" className="btn btn-sm btn-primary" disabled={busy !== null || newName.trim() === ""}>
{busy === "new" ? "Making…" : "Make group"}
</button>
<button type="button" className="btn btn-sm btn-link text-secondary" onClick={() => { setCreating(false); setNewName(""); }} disabled={busy === "new"}>
Cancel
</button>
</div>
</div>
</form>
) : (
<button type="button" className="btn btn-sm btn-primary me-2 mb-2" onClick={() => { setCreating(true); setNotice(null); setError(null); }} disabled={busy !== null}>
New group…
</button>
)}
{groups === null ? (
<button type="button" className="btn btn-sm btn-outline-secondary mb-2" onClick={() => void load()} disabled={busy !== null}>
{busy === "list" ? "Reading…" : error ? "Try again" : "Show groups"}
</button>
) : (
<>
{groups.length === 0 ? (
<div className="text-secondary mb-2">There are no groups.</div>
) : (
<div className="table-responsive">
<table className="table table-vcenter table-sm">
<thead>
<tr>
<th>Group</th>
<th className="text-end">Members</th>
<th className="text-end">&nbsp;</th>
</tr>
</thead>
<tbody>
{groups.map((g) =>
editing === g.id ? (
<tr key={g.id}>
<td colSpan={3}>
<EditGroup g={g} people={people} self={self} busy={busy === g.id} onSave={(name, add, remove) => void save(g, name, add, remove)} onCancel={() => setEditing(null)} />
</td>
</tr>
) : (
<tr key={g.id}>
<td>
{g.name}
{g.admin && <span className="badge bg-yellow-lt text-yellow ms-2">administrators</span>}
{g.decidesRole && <span className="badge bg-blue-lt text-blue ms-1">decides {g.decidesRole === "admin" ? "admins" : "operators"} here</span>}
</td>
<td className="text-end text-secondary">{g.members === null ? "?" : g.members.length}</td>
<td className="text-end text-nowrap">
<button type="button" className="btn btn-sm btn-outline-secondary me-1" disabled={busy !== null} onClick={() => { setEditing(g.id); setNotice(null); }}>
Edit
</button>
{g.admin ? (
<span className="small text-secondary" title="A group that makes administrators of Authentik is deleted in Authentik, not here.">
deleted in Authentik
</span>
) : (
<button type="button" className="btn btn-sm btn-outline-danger" disabled={busy !== null} onClick={() => void removeGroup(g)}>
Delete
</button>
)}
</td>
</tr>
),
)}
</tbody>
</table>
</div>
)}
<button type="button" className="btn btn-sm btn-link text-secondary px-0" onClick={() => { setGroups(null); setEditing(null); }}>
Hide groups
</button>
</>
)}
</div>
);
}