List, switch off/on and delete Authentik users
Apps → Authentik gets a Users section for administrators: a searchable list of people (service accounts left out) with status, administrator and last sign-in, and Switch off / Switch on / Delete. Switching off sends only is_active; deleting needs the user name typed and re-checked by the server. The server refuses service accounts, the account the token belongs to and the last active administrator. Each action is audited. The token field is now "Token for making and managing users". Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aa95d6b314
commit
0cd11268ee
12 files changed
+733
-21
No files matched your search
@@ -6,7 +6,7 @@ import { authentikState, integrationCredentials, integrations } from "../db/sche
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { decryptSecret, encryptSecret } from "../crypto.js";
|
||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||
import { AuthentikUserError, createAuthentikUsersAdapter, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
||||
import { AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
@@ -55,10 +55,21 @@ async function usersAdapterFor(rawId: string, res: Response): Promise<{ adapter:
|
||||
|
||||
/** 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 : 502).json({ error: `authentik_${err.kind}`, message: err.message });
|
||||
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);
|
||||
|
||||
/** The user as Authentik has them now, and whether this may be done to them — asked of Authentik itself, not taken from the page, which may be minutes old. */
|
||||
async function guard(adapter: AuthentikUsersAdapter, pk: number, action: "disable" | "enable" | "delete"): Promise<{ user: AuthentikUser; refusal: string | null }> {
|
||||
const user = await adapter.getUser(pk);
|
||||
if (action === "enable" || isServiceAccount(user)) return { user, refusal: refusalFor(user, action, null, []) };
|
||||
const self = await adapter.whoAmI();
|
||||
const admins = user.admin && user.active ? await adapter.activeAdmins() : [];
|
||||
return { user, refusal: refusalFor(user, action, self, admins) };
|
||||
}
|
||||
|
||||
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),
|
||||
@@ -177,3 +188,63 @@ authentikRouter.delete("/:id/write-token", requireRole("admin"), asyncHandler(as
|
||||
}
|
||||
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);
|
||||
}
|
||||
}));
|
||||
Reference in new issue
Block a user