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>
481 lines
26 KiB
TypeScript
481 lines
26 KiB
TypeScript
import { Router, type Response } from "express";
|
|
import { eq } from "drizzle-orm";
|
|
import { z } from "zod";
|
|
import { db } from "../db/client.js";
|
|
import { authentikState, integrationCredentials, integrations } from "../db/schema.js";
|
|
import { requireAuth, requireRole } from "../auth/middleware.js";
|
|
import { decryptSecret, encryptSecret } from "../crypto.js";
|
|
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
|
import { applyGroupChange, AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
|
import { roleForGroupName } from "../auth/groups.js";
|
|
import { recordAudit } from "../services/audit.js";
|
|
import { getSettings } from "../services/settingsStore.js";
|
|
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
|
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
|
|
|
export const authentikRouter = Router();
|
|
authentikRouter.use(requireAuth);
|
|
|
|
const hasWriteToken = (config: Record<string, unknown>) => typeof config.writeToken === "string" && config.writeToken.trim() !== "";
|
|
|
|
/** Whether this Authentik was given a token to make users with. Never says more than that; a credential that cannot be opened counts as none. */
|
|
async function canCreateUsers(id: number): Promise<boolean> {
|
|
try {
|
|
const loaded = await loadIntegrationConfig(id);
|
|
return !!loaded && hasWriteToken(loaded.config);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** The adapter that makes users for one Authentik, or the answer to send when there is not one to use. Only an enabled Authentik with a token for it. */
|
|
async function usersAdapterFor(rawId: string, res: Response): Promise<{ adapter: AuthentikUsersAdapter; id: number; name: string } | null> {
|
|
const id = /^\d+$/.test(rawId) ? Number(rawId) : NaN;
|
|
if (!Number.isInteger(id)) {
|
|
res.status(400).json({ error: "invalid_id" });
|
|
return null;
|
|
}
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "authentik") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled", message: "This Authentik is switched off." });
|
|
return null;
|
|
}
|
|
if (!hasWriteToken(loaded.config)) {
|
|
res.status(400).json({ error: "no_write_token", message: "This Authentik has no token for making users. Add one under Integrations → edit." });
|
|
return null;
|
|
}
|
|
return { adapter: createAuthentikUsersAdapter(loaded.config as never), id, name: loaded.integration.name };
|
|
}
|
|
|
|
/** What a failed call to Authentik is answered with: what it said when it looked and refused, a bad gateway otherwise. */
|
|
function sendFailure(res: Response, err: unknown) {
|
|
if (err instanceof AuthentikUserError) return res.status(err.kind === "invalid" ? 400 : err.kind === "missing" ? 404 : 502).json({ error: `authentik_${err.kind}`, message: err.message });
|
|
return res.status(502).json({ error: "authentik_failed", message: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
|
|
const pkOf = (raw: string) => (/^\d{1,12}$/.test(raw) ? Number(raw) : Number.NaN);
|
|
|
|
type UserAction = "disable" | "enable" | "delete" | "edit";
|
|
|
|
/** Whether this may be done to this user, asked of Authentik itself — not taken from the page, which may be minutes old. For an edit, `newGroups` is what their groups would be. */
|
|
async function judge(adapter: AuthentikUsersAdapter, user: AuthentikUser, action: UserAction, newGroups?: string[]): Promise<string | null> {
|
|
if (action === "enable" || isServiceAccount(user)) return refusalFor(user, action, null, []);
|
|
const self = await adapter.whoAmI();
|
|
const admins = user.admin && user.active ? await adapter.activeAdmins() : [];
|
|
let losesAdmin = false;
|
|
if (action === "edit" && newGroups && user.admin && user.active) {
|
|
const adminGroups = new Set((await adapter.listGroups()).filter((g) => g.admin).map((g) => g.id));
|
|
losesAdmin = !newGroups.some((g) => adminGroups.has(g));
|
|
}
|
|
return refusalFor(user, action, self, admins, losesAdmin);
|
|
}
|
|
|
|
/** The user as Authentik has them now, and whether this may be done to them. */
|
|
async function guard(adapter: AuthentikUsersAdapter, pk: number, action: Exclude<UserAction, "edit">): Promise<{ user: AuthentikUser; refusal: string | null }> {
|
|
const user = await adapter.getUser(pk);
|
|
return { user, refusal: await judge(adapter, user, action) };
|
|
}
|
|
|
|
const newUserSchema = z.object({
|
|
username: z.string().trim().min(1, "A user name is needed.").max(150).regex(/^[^\x00-\x1f\x7f]+$/, "A user name can't hold control characters."),
|
|
name: z.string().trim().min(1, "A name is needed.").max(200),
|
|
email: z.union([z.literal(""), z.string().trim().email("That is not an email address.").max(254)]).optional(),
|
|
groups: z.array(z.string().uuid()).max(50).default([]),
|
|
});
|
|
|
|
/** Every Authentik, how it is, from what the last read stored: its outposts, certificates and tokens that run out, and what is wrong. Everyone signed in can see it, like the other pages made of stored readings. */
|
|
authentikRouter.get("/", asyncHandler(async (_req, res) => {
|
|
const [rows, states, statuses] = await Promise.all([
|
|
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "authentik")).orderBy(integrations.name),
|
|
db.select().from(authentikState),
|
|
authentikSyncStatuses(),
|
|
]);
|
|
const byId = new Map(states.map((s) => [s.integrationId, s]));
|
|
const writable = new Map(await Promise.all(rows.map(async (r) => [r.id, await canCreateUsers(r.id)] as const)));
|
|
const now = new Date();
|
|
res.json({
|
|
authentiks: rows.map((r) => {
|
|
const state = byId.get(r.id) ?? null;
|
|
const status = statuses[r.id] ?? null;
|
|
const fresh = isAuthentikFresh(status ?? undefined, now.getTime());
|
|
return {
|
|
id: r.id,
|
|
name: r.name,
|
|
enabled: r.enabled,
|
|
canCreateUsers: r.enabled && writable.get(r.id) === true,
|
|
status,
|
|
fresh,
|
|
state: state
|
|
? {
|
|
version: state.version,
|
|
latestVersion: state.latestVersion,
|
|
outdated: state.outdated,
|
|
workers: state.workers,
|
|
outposts: outpostsOf(state),
|
|
certificates: certificatesOf(state).map((c) => ({ ...c, days: daysUntil(c.expires, now) })).sort((a, b) => a.days - b.days),
|
|
tokens: tokensOf(state).map((t) => ({ ...t, days: daysUntil(t.expires, now) })).sort((a, b) => a.days - b.days),
|
|
failedLogins24h: state.failedLogins24h,
|
|
configErrors24h: state.configErrors24h,
|
|
lastConfigError: state.lastConfigError,
|
|
updatedAt: state.updatedAt,
|
|
}
|
|
: null,
|
|
problems: state && fresh ? authentikProblems(r.id, r.name, state, now) : [],
|
|
};
|
|
}),
|
|
});
|
|
}));
|
|
|
|
/** The groups a new user can be put in, as the Authentik being asked has them. Only an administrator, and only where a token for making users was given. */
|
|
authentikRouter.get("/:id/groups", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
try {
|
|
res.json({ groups: await target.adapter.listGroups() });
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
/**
|
|
* Makes a user and a one-time recovery link for them, which is how they choose their own password: no password passes through here. The link is in this answer and nowhere else — not stored,
|
|
* not in the audit log. When the user is made and the link is not, the answer says so and the link is made in Authentik (the user's page → Create recovery link).
|
|
*/
|
|
authentikRouter.post("/:id/users", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = newUserSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a user.", details: parsed.error.flatten() });
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
|
|
let user;
|
|
try {
|
|
user = await target.adapter.createUser({ username: parsed.data.username, name: parsed.data.name, email: parsed.data.email || undefined, groups: parsed.data.groups });
|
|
} catch (err) {
|
|
return sendFailure(res, err);
|
|
}
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "create_authentik_user",
|
|
targetType: "authentik_user",
|
|
targetId: user.pk,
|
|
detail: { integrationId: target.id, integration: target.name, username: user.username, groups: parsed.data.groups.length },
|
|
});
|
|
|
|
let link: string | null = null;
|
|
let linkError: string | null = null;
|
|
try {
|
|
link = await target.adapter.recoveryLink(user.pk);
|
|
await recordAudit({ actor: req.currentUser!, category: "integration", action: "make_authentik_recovery_link", targetType: "authentik_user", targetId: user.pk, detail: { integrationId: target.id, username: user.username } });
|
|
} catch (err) {
|
|
linkError = err instanceof Error ? err.message : String(err);
|
|
}
|
|
res.set("Cache-Control", "no-store");
|
|
res.status(201).json({ user, link, linkError });
|
|
}));
|
|
|
|
/** Takes the token for making users away again, leaving the one that reads. */
|
|
authentikRouter.delete("/:id/write-token", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN;
|
|
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
|
const [row] = await db.select().from(integrations).where(eq(integrations.id, id)).limit(1);
|
|
if (!row) return res.status(404).json({ error: "not_found" });
|
|
if (row.type !== "authentik") return res.status(400).json({ error: "wrong_type" });
|
|
if (row.credentialId) {
|
|
const [cred] = await db.select().from(integrationCredentials).where(eq(integrationCredentials.id, row.credentialId)).limit(1);
|
|
if (cred) {
|
|
const secrets = JSON.parse(decryptSecret(cred.encryptedSecret)) as Record<string, unknown>;
|
|
if ("writeToken" in secrets) {
|
|
delete secrets.writeToken;
|
|
await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify(secrets)) }).where(eq(integrationCredentials.id, cred.id));
|
|
await recordAudit({ actor: req.currentUser!, category: "integration", action: "remove_authentik_write_token", targetType: "integration", targetId: id, detail: { name: row.name } });
|
|
}
|
|
}
|
|
}
|
|
res.status(204).end();
|
|
}));
|
|
|
|
/** The people in that Authentik, for the page that looks after them: not the service accounts, and which one the token belongs to (that one is not touched). Only an administrator. */
|
|
authentikRouter.get("/:id/users", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
const search = typeof req.query.search === "string" ? req.query.search.trim().slice(0, 100) : "";
|
|
try {
|
|
const [list, self] = await Promise.all([target.adapter.listUsers(search), target.adapter.whoAmI()]);
|
|
res.json({ users: list.users, more: list.more, self });
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
const activeSchema = z.object({ active: z.boolean() });
|
|
|
|
/** Switches a user off or on again. Off means they can no longer sign in at Authentik; nothing of theirs is lost, and on brings it all back. */
|
|
authentikRouter.post("/:id/users/:pk/active", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = activeSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say whether the user is to be on or off." });
|
|
const pk = pkOf(req.params.pk);
|
|
if (!Number.isInteger(pk) || pk <= 0) return res.status(400).json({ error: "invalid_user" });
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
const action = parsed.data.active ? "enable" : "disable";
|
|
try {
|
|
const { user, refusal } = await guard(target.adapter, pk, action);
|
|
if (refusal) return res.status(409).json({ error: "refused", message: refusal });
|
|
const updated = await target.adapter.setActive(pk, parsed.data.active);
|
|
await recordAudit({ actor: req.currentUser!, category: "integration", action: `${action}_authentik_user`, targetType: "authentik_user", targetId: pk, detail: { integrationId: target.id, integration: target.name, username: user.username } });
|
|
res.json({ user: updated });
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
const deleteSchema = z.object({ username: z.string().min(1).max(150) });
|
|
|
|
/**
|
|
* Deletes a user for good. The user name has to be sent along and has to be the one the user has now: a page that is minutes old, or a wrong id, cannot delete somebody else. Switching off
|
|
* is the way that can be undone; this is not.
|
|
*/
|
|
authentikRouter.delete("/:id/users/:pk", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = deleteSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "The user name has to be sent along to delete a user." });
|
|
const pk = pkOf(req.params.pk);
|
|
if (!Number.isInteger(pk) || pk <= 0) return res.status(400).json({ error: "invalid_user" });
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
try {
|
|
const { user, refusal } = await guard(target.adapter, pk, "delete");
|
|
if (user.username !== parsed.data.username) return res.status(400).json({ error: "username_mismatch", message: "That is not the user name of that user." });
|
|
if (refusal) return res.status(409).json({ error: "refused", message: refusal });
|
|
await target.adapter.deleteUser(pk);
|
|
await recordAudit({ actor: req.currentUser!, category: "integration", action: "delete_authentik_user", targetType: "authentik_user", targetId: pk, detail: { integrationId: target.id, integration: target.name, username: user.username } });
|
|
res.status(204).end();
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
const editSchema = z
|
|
.object({
|
|
name: z.string().trim().min(1, "A name is needed.").max(200).optional(),
|
|
// An empty email clears it.
|
|
email: z.union([z.literal(""), z.string().trim().email("That is not an email address.").max(254)]).optional(),
|
|
// Groups are changed by what to put in and what to take out, never by a whole list: a membership somebody gave them meanwhile is kept.
|
|
groupsAdd: z.array(z.string().uuid()).max(50).default([]),
|
|
groupsRemove: z.array(z.string().uuid()).max(50).default([]),
|
|
})
|
|
.refine((d) => !d.groupsAdd.some((g) => d.groupsRemove.includes(g)), { message: "A group can't be both put in and taken out." });
|
|
|
|
/**
|
|
* Changes a user's name, email and groups — what they are called and where they belong; not the user name, which is how a person is known elsewhere. Authentik is sent only what differs
|
|
* from the user as it has them now (nothing at all when nothing does), and the groups as that user's current ones with the changes made.
|
|
*/
|
|
authentikRouter.patch("/:id/users/:pk", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = editSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a change.", details: parsed.error.flatten() });
|
|
const pk = pkOf(req.params.pk);
|
|
if (!Number.isInteger(pk) || pk <= 0) return res.status(400).json({ error: "invalid_user" });
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
const { name, email, groupsAdd, groupsRemove } = parsed.data;
|
|
try {
|
|
const user = await target.adapter.getUser(pk);
|
|
const changes: { name?: string; email?: string; groups?: string[] } = {};
|
|
if (name !== undefined && name !== user.name) changes.name = name;
|
|
if (email !== undefined && email !== (user.email ?? "")) changes.email = email;
|
|
let newGroups: string[] | undefined;
|
|
if (groupsAdd.length > 0 || groupsRemove.length > 0) {
|
|
if (user.groups === null) return res.status(409).json({ error: "refused", message: "Authentik did not say which groups this user is in, so they are not changed from here." });
|
|
const next = applyGroupChange(user.groups, groupsAdd, groupsRemove);
|
|
if (next.length !== user.groups.length || next.some((g) => !user.groups!.includes(g))) {
|
|
changes.groups = next;
|
|
newGroups = next;
|
|
}
|
|
}
|
|
const changed = Object.keys(changes);
|
|
if (changed.length === 0) return res.json({ user, changed });
|
|
const refusal = await judge(target.adapter, user, "edit", newGroups);
|
|
if (refusal) return res.status(409).json({ error: "refused", message: refusal });
|
|
const updated = await target.adapter.updateUser(pk, changes);
|
|
await recordAudit({ actor: req.currentUser!, category: "integration", action: "update_authentik_user", targetType: "authentik_user", targetId: pk, detail: { integrationId: target.id, integration: target.name, username: user.username, changed } });
|
|
res.json({ user: updated, changed });
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
const GROUP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
|
|
/**
|
|
* The groups with who is in each, for the page that looks after them — and the people to name the members by (not the service accounts), and which one the token is. Every group says
|
|
* whether it decides somebody's role in this app (Settings → Sign-in), because changing its name or its members changes that at their next sign-in.
|
|
*/
|
|
authentikRouter.get("/:id/group-details", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
try {
|
|
const [groups, people, self, settings] = await Promise.all([target.adapter.listGroupDetails(), target.adapter.listUsers(), target.adapter.whoAmI(), getSettings()]);
|
|
res.json({
|
|
groups: groups.map((g) => ({ ...g, decidesRole: roleForGroupName(settings.signIn, g.name) })),
|
|
people: people.users.map((u) => ({ pk: u.pk, username: u.username, name: u.name, active: u.active })),
|
|
more: people.more,
|
|
self,
|
|
});
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
const groupEditSchema = z
|
|
.object({
|
|
name: z.string().trim().min(1, "A group needs a name.").max(200).optional(),
|
|
// Members are changed by who goes in and who comes out, never by a whole list: somebody who joined meanwhile is not dropped.
|
|
membersAdd: z.array(z.number().int().positive()).max(25).default([]),
|
|
membersRemove: z.array(z.number().int().positive()).max(25).default([]),
|
|
})
|
|
.refine((d) => !d.membersAdd.some((m) => d.membersRemove.includes(m)), { message: "A user can't be both put in and taken out." });
|
|
|
|
/**
|
|
* Renames a group and/or puts users in it and takes them out. Everything is checked first, against Authentik as it is now, and nothing is changed if anything is refused — a service account, the
|
|
* account the token belongs to, someone whose groups Authentik did not say (when taking them out of a group that makes administrators), or the last active administrator losing that. Then the
|
|
* name, then the users one by one; if Authentik fails part-way the answer says how far it got and the audit log has what was done. Whether the group makes administrators is not changed here.
|
|
*/
|
|
authentikRouter.patch("/:id/groups/:gid", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = groupEditSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a change.", details: parsed.error.flatten() });
|
|
const gid = req.params.gid;
|
|
if (!GROUP_ID.test(gid)) return res.status(400).json({ error: "invalid_group" });
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
const { adapter } = target;
|
|
const { name, membersAdd, membersRemove } = parsed.data;
|
|
try {
|
|
const group = await adapter.getGroup(gid);
|
|
const rename = name !== undefined && name !== group.name ? name : null;
|
|
let add: number[] = [];
|
|
let remove: number[] = [];
|
|
if (membersAdd.length > 0 || membersRemove.length > 0) {
|
|
if (group.members === null) return res.status(409).json({ error: "refused", message: "Authentik did not say who is in this group, so its members are not changed from here." });
|
|
add = membersAdd.filter((m) => !group.members!.includes(m));
|
|
remove = membersRemove.filter((m) => group.members!.includes(m));
|
|
}
|
|
if (rename === null && add.length === 0 && remove.length === 0) return res.json({ changed: [], added: 0, removed: 0 });
|
|
|
|
// Look at everyone first: nothing is changed unless all of it may be.
|
|
const people = new Map<number, AuthentikUser>();
|
|
for (const pk of [...add, ...remove]) {
|
|
const user = await adapter.getUser(pk);
|
|
people.set(pk, user);
|
|
let refusal: string | null;
|
|
if (remove.includes(pk) && group.admin && user.groups === null && !isServiceAccount(user)) refusal = "Authentik did not say which groups they are in, so they are not taken out of a group that makes administrators from here.";
|
|
else refusal = await judge(adapter, user, "edit", remove.includes(pk) && group.admin && user.groups ? user.groups.filter((g) => g !== gid) : undefined);
|
|
if (refusal) return res.status(409).json({ error: "refused", message: `${user.username}: ${refusal}` });
|
|
}
|
|
|
|
const total = (rename === null ? 0 : 1) + add.length + remove.length;
|
|
let done = 0;
|
|
const doneAdded: string[] = [];
|
|
const doneRemoved: string[] = [];
|
|
let failure: unknown = null;
|
|
try {
|
|
if (rename !== null) {
|
|
await adapter.renameGroup(gid, rename);
|
|
done += 1;
|
|
}
|
|
for (const pk of add) {
|
|
await adapter.addMember(gid, pk);
|
|
done += 1;
|
|
doneAdded.push(people.get(pk)!.username);
|
|
}
|
|
for (const pk of remove) {
|
|
await adapter.removeMember(gid, pk);
|
|
done += 1;
|
|
doneRemoved.push(people.get(pk)!.username);
|
|
}
|
|
} catch (err) {
|
|
failure = err;
|
|
}
|
|
if (done > 0) {
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "update_authentik_group",
|
|
targetType: "authentik_group",
|
|
targetId: gid,
|
|
detail: { integrationId: target.id, integration: target.name, group: group.name, ...(rename !== null && done > 0 ? { renamedTo: rename } : {}), added: doneAdded, removed: doneRemoved },
|
|
});
|
|
}
|
|
if (failure !== null) {
|
|
const kind = failure instanceof AuthentikUserError ? failure.kind : "failed";
|
|
const message = failure instanceof Error ? failure.message : String(failure);
|
|
return sendFailure(res, new AuthentikUserError(`${message} — ${done} of ${total} changes had been made`, kind));
|
|
}
|
|
res.json({ changed: [...(rename !== null ? ["name"] : []), ...(add.length + remove.length > 0 ? ["members"] : [])], added: add.length, removed: remove.length });
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
const newGroupSchema = z.object({ name: z.string().trim().min(1, "A group needs a name.").max(200) });
|
|
|
|
/**
|
|
* Makes a group: a name, nothing else — it has no members (they are put in with the editor, which asks first where a group decides roles here) and it is never one that makes administrators of
|
|
* Authentik. A name Authentik already has is its own refusal. The answer says whether the new name decides a role in this app, so the page can say what putting someone in it would mean.
|
|
*/
|
|
authentikRouter.post("/:id/groups", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = newGroupSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a group.", details: parsed.error.flatten() });
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
try {
|
|
const group = await target.adapter.createGroup(parsed.data.name);
|
|
await recordAudit({ actor: req.currentUser!, category: "integration", action: "create_authentik_group", targetType: "authentik_group", targetId: group.id, detail: { integrationId: target.id, integration: target.name, group: group.name } });
|
|
const settings = await getSettings();
|
|
res.status(201).json({ group: { ...group, decidesRole: roleForGroupName(settings.signIn, group.name) } });
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|
|
|
|
const deleteGroupSchema = z.object({ name: z.string().min(1).max(200) });
|
|
|
|
/**
|
|
* Deletes a group for good; its members stay, just not in it. The group's name has to be sent along and has to be the one it has now (a page that is minutes old cannot delete another group),
|
|
* and a group that makes its members administrators of Authentik is refused: deleting it would take that from all of them at once, possibly from the last administrator. A group that decides
|
|
* roles in this app (Settings → Sign-in) may be deleted — the page asks first — and the audit log says it was one.
|
|
*/
|
|
authentikRouter.delete("/:id/groups/:gid", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = deleteGroupSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "The name of the group has to be sent along to delete it." });
|
|
const gid = req.params.gid;
|
|
if (!GROUP_ID.test(gid)) return res.status(400).json({ error: "invalid_group" });
|
|
const target = await usersAdapterFor(req.params.id, res);
|
|
if (!target) return;
|
|
try {
|
|
const group = await target.adapter.getGroup(gid);
|
|
if (group.name !== parsed.data.name) return res.status(400).json({ error: "name_mismatch", message: "That is not the name of that group." });
|
|
if (group.admin) return res.status(409).json({ error: "refused", message: "That group makes its members administrators of Authentik; deleting it would take that from all of them at once. Do it in Authentik if you mean to." });
|
|
const settings = await getSettings();
|
|
await target.adapter.deleteGroup(gid);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "delete_authentik_group",
|
|
targetType: "authentik_group",
|
|
targetId: gid,
|
|
detail: { integrationId: target.id, integration: target.name, group: group.name, members: group.members?.length ?? null, decidesRole: roleForGroupName(settings.signIn, group.name) },
|
|
});
|
|
res.status(204).end();
|
|
} catch (err) {
|
|
sendFailure(res, err);
|
|
}
|
|
}));
|