Edit Authentik users: name, email and groups

Each person in Apps → Authentik → Users gets an Edit form. The user name is
shown but not changeable. Authentik is sent only what differs, and groups as
what goes in and what comes out on top of the user's current groups, so a
membership added meanwhile is kept; a user whose groups Authentik doesn't
report can't have them changed. The server refuses service accounts, the
token's own account, and an edit that would leave no active administrator.
Audited by field name, never by value.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 00:39:51 +01:00
1 parent 0cd11268ee
commit 3618cb3ae8
9 files changed
+370 -30

No files matched your search

+3 -3
View File
@@ -526,10 +526,10 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
The link is in the answer to that one request and nowhere else (not stored, not in the audit log); the audit log has *who made which user* and *who made a link for whom*, never the link or a token. If the user is made and the link is not (Authentik needs a **recovery flow** on the brand — System → Brands), The link is in the answer to that one request and nowhere else (not stored, not in the audit log); the audit log has *who made which user* and *who made a link for whom*, never the link or a token. If the user is made and the link is not (Authentik needs a **recovery flow** on the brand — System → Brands),
the page says so and the link is made in Authentik (the user → *Create recovery link*). Authentik builds the link from the address it was called at, so the integration's address should be the one people use. The token for making users is only used for this; reading Authentik never uses it, the page says so and the link is made in Authentik (the user → *Create recovery link*). Authentik builds the link from the address it was called at, so the integration's address should be the one people use. The token for making users is only used for this; reading Authentik never uses it,
and *Stop allowing this* on the page removes it again (the reading token stays). and *Stop allowing this* on the page removes it again (the reading token stays).
**Users** on the same page lists the people (service accounts — what an outpost or an integration signs in with — are left out), searchable, with whether each is on, whether they are an administrator and when they last signed in, and lets an administrator **switch a user off** (a `PATCH` of `is_active` and nothing else; **Users** on the same page lists the people (service accounts — what an outpost or an integration signs in with — are left out), searchable, with whether each is on, whether they are an administrator and when they last signed in, and lets an administrator **edit a user's name, email and groups** (the user name is shown but not changeable: it is how a person is known elsewhere, and renaming could make them a new person here; Authentik is sent only what differs, as a `PATCH`, and groups as what goes in and what comes out on top of the groups the user has *now*, so a membership somebody gave them meanwhile is kept; a user whose groups Authentik does not say can be renamed but not moved between groups), **switch a user off** (a `PATCH` of `is_active` and nothing else;
they can no longer sign in, nothing of theirs is lost, *Switch on* brings it back) or **delete** one (a `DELETE`, for good: the user name has to be typed, and is checked again by the server against the user as Authentik has them now). **Refused, by the server, with the reason:** a service account, the account the token they can no longer sign in, nothing of theirs is lost, *Switch on* brings it back) or **delete** one (a `DELETE`, for good: the user name has to be typed, and is checked again by the server against the user as Authentik has them now). **Refused, by the server, with the reason:** a service account, the account the token
itself belongs to, and the last active administrator (so nobody can be locked out, or the sign-in in front of everything else cut off); do those in Authentik. Each is in the audit log (*who switched off / on / deleted which user*). Switching off or deleting someone in Authentik does not end a session they itself belongs to, and the last active administrator (so nobody can be locked out, or the sign-in in front of everything else cut off — for an edit, only when it would take them out of every group that makes them one); do those in Authentik. Each is in the audit log (*who edited — which fields, never their new values — switched off / on / deleted which user*). Switching off or deleting someone in Authentik does not end a session they
already have in this app: end it under Users → *Signed in now*. Lists are read 200 at a time. Without it nothing about the page changes for anyone but an administrator, who sees where to add one. The calls (`GET /core/groups/`, `POST /core/users/`, `POST /core/users/{id}/recovery/`, `GET /core/users/`, `GET /core/users/{id}/`, `GET /core/users/me/`, `PATCH` and `DELETE /core/users/{id}/`; asking for a link that lasts a day, which a version of already have in this app: end it under Users → *Signed in now*. Lists are read 200 at a time. Without it nothing about the page changes for anyone but an administrator, who sees where to add one. The calls (`GET /core/groups/`, `POST /core/users/`, `POST /core/users/{id}/recovery/`, `GET /core/users/`, `GET /core/users/{id}/`, `GET /core/users/me/`, `PATCH` (`is_active`, or `name`, `email` and `groups`) and `DELETE /core/users/{id}/`; asking for a link that lasts a day, which a version of
Authentik that does not take that sets for itself) are **not verified against a live Authentik**; the tests use a pretend one. Authentik that does not take that sets for itself) are **not verified against a live Authentik**; the tests use a pretend one.
- **What it does:** every **five minutes** Authentik is read and stored — its version (and whether a newer one is out), whether a **worker** is connected, each **outpost** (the proxy outpost that guards your apps, an LDAP one) with how many instances reported in during the last five minutes and whether they run the right version, the - **What it does:** every **five minutes** Authentik is read and stored — its version (and whether a newer one is out), whether a **worker** is connected, each **outpost** (the proxy outpost that guards your apps, an LDAP one) with how many instances reported in during the last five minutes and whether they run the right version, the
**certificates** (those Authentik does not renew by itself) with their expiry, the **API tokens and app passwords** that expire, and how many **sign-ins failed** and **configuration errors** happened in the last day. **Apps → Authentik** shows it, with what runs out soonest first. **certificates** (those Authentik does not renew by itself) with their expiry, the **API tokens and app passwords** that expire, and how many **sign-ins failed** and **configuration errors** happened in the last day. **Apps → Authentik** shows it, with what runs out soonest first.
+1 -1
View File
@@ -572,7 +572,7 @@ quietly never made. The page shows the photo and video counts, what the library
**Authentik** (Apps → Authentik). Add an Authentik integration (its address and an API token) and the app watches the sign-in in front of everything else: it raises a **critical** alert when an **outpost** that guards applications stops reporting, and warns when a **certificate** or an **API token** is **Authentik** (Apps → Authentik). Add an Authentik integration (its address and an API token) and the app watches the sign-in in front of everything else: it raises a **critical** alert when an **outpost** that guards applications stops reporting, and warns when a **certificate** or an **API token** is
about to run out (the token it reads Authentik with included), when **no worker** is connected, and when **sign-ins are failing** or flows are misconfigured. The page lists the outposts, what runs out soonest and the failed sign-ins of the last day. See INTEGRATIONS.md and docs/MONITORING.md. about to run out (the token it reads Authentik with included), when **no worker** is connected, and when **sign-ins are failing** or flows are misconfigured. The page lists the outposts, what runs out soonest and the failed sign-ins of the last day. See INTEGRATIONS.md and docs/MONITORING.md.
An administrator can also **make a user** from that page — with a second, optional token for it — and gets a **one-time recovery link** to send them, so they choose their own password; no password is ever set or seen here, and the link is shown once and not kept. The same page lists the users and lets an administrator **switch one off** (and on again) or **delete** one (the user name has to be typed); service accounts, the account the token belongs to and the last active administrator are refused. An administrator can also **make a user** from that page — with a second, optional token for it — and gets a **one-time recovery link** to send them, so they choose their own password; no password is ever set or seen here, and the link is shown once and not kept. The same page lists the users and lets an administrator **edit** one (name, email, groups), **switch one off** (and on again) or **delete** one (the user name has to be typed); service accounts, the account the token belongs to and the last active administrator are refused.
**Jellyfin** (Apps → Jellyfin). Add a Jellyfin integration (its address and an API key) and the app shows whether it is up, **who is streaming what** and whether it is being transcoded, the scheduled tasks that failed, and a chart of how many watched at once; it warns when Jellyfin **wants a restart**, a **Jellyfin** (Apps → Jellyfin). Add a Jellyfin integration (its address and an API key) and the app shows whether it is up, **who is streaming what** and whether it is being transcoded, the scheduled tasks that failed, and a chart of how many watched at once; it warns when Jellyfin **wants a restart**, a
**task failed** or **sign-ins are failing**. And when the Jellyfin runs on a server the app manages, **an update run asks first if people are watching**, and a patch plan **waits for them (up to two hours)** instead of restarting the machine in the middle of a film. See INTEGRATIONS.md and docs/MONITORING.md. **task failed** or **sign-ins are failing**. And when the Jellyfin runs on a server the app manages, **an update run asks first if people are watching**, and a patch plan **waits for them (up to two hours)** instead of restarting the machine in the middle of a film. See INTEGRATIONS.md and docs/MONITORING.md.
+1 -1
View File
@@ -163,7 +163,7 @@ even further, to admin only:
- **Immich** (Apps → Immich): everyone signed in sees the counts, the disk and the job queues; adding one (its address and API key) is an administrator's job, like any integration. - **Immich** (Apps → Immich): everyone signed in sees the counts, the disk and the job queues; adding one (its address and API key) is an administrator's job, like any integration.
- **Paperless-ngx** (Apps → Paperless): everyone signed in sees the counts, the system status and the names of the files that failed to import; adding one (its address and a superuser's token) is an administrator's job, like any integration. - **Paperless-ngx** (Apps → Paperless): everyone signed in sees the counts, the system status and the names of the files that failed to import; adding one (its address and a superuser's token) is an administrator's job, like any integration.
- **Prometheus** (Monitoring → Prometheus): everyone signed in sees the targets, what is down and the alerts firing; adding one (its address, and a token if it needs one) is an administrator's job, like any integration. - **Prometheus** (Monitoring → Prometheus): everyone signed in sees the targets, what is down and the alerts firing; adding one (its address, and a token if it needs one) is an administrator's job, like any integration.
- **Authentik** (Apps → Authentik): everyone signed in sees the outposts, what runs out and the failed-sign-in count (the names of tokens and certificates, not their values); adding one (its address and API token) is an administrator's job, like any integration. **Making a user** there (and the groups to offer), **listing** the users and **switching them off or on or deleting them** are an administrator's alone, and only for an Authentik that was given a token for it; each is written in the audit log (who made, switched off, switched on or deleted which user, and who made a recovery link), never the link. - **Authentik** (Apps → Authentik): everyone signed in sees the outposts, what runs out and the failed-sign-in count (the names of tokens and certificates, not their values); adding one (its address and API token) is an administrator's job, like any integration. **Making a user** there (and the groups to offer), **listing** the users and **editing, switching them off or on or deleting them** are an administrator's alone, and only for an Authentik that was given a token for it; each is written in the audit log (who made, edited (which fields, not the new values), switched off, switched on or deleted which user, and who made a recovery link), never the link.
- **Jellyfin** (Apps → Jellyfin): everyone signed in sees who is streaming and what is wrong; adding one (its address and API key) is an administrator's job, like any integration. Starting an update run on a server people are streaming from needs `startAnyway` — the update drawer asks (operators). - **Jellyfin** (Apps → Jellyfin): everyone signed in sees who is streaming and what is wrong; adding one (its address and API key) is an administrator's job, like any integration. Starting an update run on a server people are streaming from needs `startAnyway` — the update drawer asks (operators).
- **Media managers** (Apps → Media managers, for Sonarr, Radarr and Prowlarr): everyone signed in sees what each says is wrong, its queue, disks and indexers; adding one (its API key) is an administrator's job, like any integration. Nothing on the page changes anything in them. - **Media managers** (Apps → Media managers, for Sonarr, Radarr and Prowlarr): everyone signed in sees what each says is wrong, its queue, disks and indexers; adding one (its API key) is an administrator's job, like any integration. Nothing on the page changes anything in them.
- **App versions** (Operations → App versions): everyone signed in sees what each application runs against the newest release; switching the lookup of releases on and off, and the number of days after which a newer release is a warning, are an administrator's. - **App versions** (Operations → App versions): everyone signed in sees what each application runs against the newest release; switching the lookup of releases on and off, and the number of days after which a newer release is a warning, are an administrator's.
+33 -9
View File
@@ -5,8 +5,8 @@
* Making one takes three calls: the groups to offer (`GET /core/groups/`), the user (`POST /core/users/`) and a one-time recovery link for that user (`POST /core/users/{pk}/recovery/`), which is how the * Making one takes three calls: the groups to offer (`GET /core/groups/`), the user (`POST /core/users/`) and a one-time recovery link for that user (`POST /core/users/{pk}/recovery/`), which is how the
* person gets to choose their own password: this app never sets, sees or keeps one. The link is handed back once and not stored. * person gets to choose their own password: this app never sets, sees or keeps one. The link is handed back once and not stored.
* *
* Looking after them: the users (`GET /core/users/`, one `GET /core/users/{pk}/`), who the token is (`GET /core/users/me/`), switching one off or on (`PATCH /core/users/{pk}/` with only `is_active`) and * Looking after them: the users (`GET /core/users/`, one `GET /core/users/{pk}/`), who the token is (`GET /core/users/me/`), switching one off or on (`PATCH /core/users/{pk}/` with only `is_active`),
* deleting one (`DELETE /core/users/{pk}/`). Service accounts — what an outpost or an integration signs in with — are not listed and are refused, and so are the account the token belongs to and the last * changing their name, email and groups (the same `PATCH`, with only what changed — never the user name, which is how a person is known elsewhere) and deleting one (`DELETE /core/users/{pk}/`). Service accounts — what an outpost or an integration signs in with — are not listed and are refused, and so are the account the token belongs to and the last
* active administrator, so this cannot be used to lock everyone out or to cut off the sign-in in front of everything else. * active administrator, so this cannot be used to lock everyone out or to cut off the sign-in in front of everything else.
* *
* Endpoints and field names are from Authentik's published API and have not been checked against a live server here; every field is read defensively. The link is built by Authentik from * Endpoints and field names are from Authentik's published API and have not been checked against a live server here; every field is read defensively. The link is built by Authentik from
@@ -107,6 +107,8 @@ export interface AuthentikUser {
lastLogin: string | null; lastLogin: string | null;
/** internal, external, service_account, internal_service_account. */ /** internal, external, service_account, internal_service_account. */
type: string; type: string;
/** Group ids; null when Authentik did not say, which is not the same as none — and then they are not changed from here. */
groups: string[] | null;
} }
/** What an outpost or an integration signs in with: not a person, and not this app's to switch off or delete. */ /** What an outpost or an integration signs in with: not a person, and not this app's to switch off or delete. */
@@ -118,7 +120,7 @@ export function parseUser(raw: unknown): AuthentikUser | null {
const pk = typeof u.pk === "number" ? u.pk : Number.NaN; const pk = typeof u.pk === "number" ? u.pk : Number.NaN;
const username = str(u.username); const username = str(u.username);
if (!Number.isInteger(pk) || pk <= 0 || !username) return null; if (!Number.isInteger(pk) || pk <= 0 || !username) return null;
return { pk, username, name: str(u.name) ?? username, email: str(u.email), active: u.is_active !== false, admin: u.is_superuser === true, lastLogin: iso(u.last_login), type: str(u.type) ?? "internal" }; return { pk, username, name: str(u.name) ?? username, email: str(u.email), active: u.is_active !== false, admin: u.is_superuser === true, lastLogin: iso(u.last_login), type: str(u.type) ?? "internal", groups: Array.isArray(u.groups) ? u.groups.filter((g): g is string => typeof g === "string" && UUID.test(g)) : null };
} }
/** Pure: the people of a `/core/users/` page (service accounts left out), and whether there are more pages than this one. */ /** Pure: the people of a `/core/users/` page (service accounts left out), and whether there are more pages than this one. */
@@ -134,15 +136,25 @@ export function parseMe(raw: unknown): number | null {
return typeof pk === "number" && Number.isInteger(pk) && pk > 0 ? pk : null; return typeof pk === "number" && Number.isInteger(pk) && pk > 0 ? pk : null;
} }
/** Pure: the groups a user is in after taking some out and putting some in, from the groups they are in now — so a membership somebody else gave them meanwhile is kept. */
export function applyGroupChange(current: string[], add: string[], remove: string[]): string[] {
const out = current.filter((g) => !remove.includes(g));
for (const g of add) if (!out.includes(g)) out.push(g);
return out;
}
/** /**
* Pure: why this must not be done to this user, or null when it may. A service account is never touched. Switching on is always fine. Switching off or deleting is not for the account the token * Pure: why this must not be done to this user, or null when it may. A service account is never touched. Switching on is always fine. Switching off, deleting or changing is not for the account the
* belongs to (the app would cut off its own hand) nor for the only active administrator left (nobody could sign in to put it right). * token belongs to (the app would cut off its own hand) nor, when it would leave Authentik without one (`losesAdmin`: an edit that takes them out of every group that makes them an administrator),
* for the only active administrator left (nobody could sign in to put it right).
*/ */
export function refusalFor(user: AuthentikUser, action: "disable" | "enable" | "delete", self: number | null, activeAdmins: number[]): string | null { export function refusalFor(user: AuthentikUser, action: "disable" | "enable" | "delete" | "edit", self: number | null, activeAdmins: number[], losesAdmin = false): string | null {
if (isServiceAccount(user)) return "That is a service account — an outpost or an integration signs in with it. It is looked after in Authentik."; if (isServiceAccount(user)) return "That is a service account — an outpost or an integration signs in with it. It is looked after in Authentik.";
if (action === "enable") return null; if (action === "enable") return null;
if (self !== null && user.pk === self) return "That is the account the token for managing users belongs to; switching it off or deleting it would cut off this very access. Do it in Authentik if you mean to."; if (self !== null && user.pk === self) return "That is the account the token for managing users belongs to; switching it off, deleting it or changing it from here could cut off this very access. Do it in Authentik if you mean to.";
if (user.admin && user.active && activeAdmins.includes(user.pk) && activeAdmins.length <= 1) return "That is the only active administrator Authentik has; with it gone nobody could sign in to put things right. Do it in Authentik if you mean to."; const onlyAdmin = user.admin && user.active && activeAdmins.includes(user.pk) && activeAdmins.length <= 1;
if (onlyAdmin && (action === "disable" || action === "delete")) return "That is the only active administrator Authentik has; with it gone nobody could sign in to put things right. Do it in Authentik if you mean to.";
if (onlyAdmin && action === "edit" && losesAdmin) return "That is the only active administrator Authentik has; taking them out of the groups that make them one would leave nobody able to sign in to put things right. Do it in Authentik if you mean to.";
return null; return null;
} }
@@ -166,6 +178,7 @@ export interface AuthentikUsersAdapter {
/** The pks of the active administrators (people), enough of them to tell whether there is more than one. */ /** The pks of the active administrators (people), enough of them to tell whether there is more than one. */
activeAdmins(): Promise<number[]>; activeAdmins(): Promise<number[]>;
setActive(pk: number, active: boolean): Promise<AuthentikUser>; setActive(pk: number, active: boolean): Promise<AuthentikUser>;
updateUser(pk: number, changes: { name?: string; email?: string; groups?: string[] }): Promise<AuthentikUser>;
deleteUser(pk: number): Promise<void>; deleteUser(pk: number): Promise<void>;
listGroups(): Promise<AuthentikGroup[]>; listGroups(): Promise<AuthentikGroup[]>;
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>; createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
@@ -224,6 +237,17 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return user; return user;
} }
async function updateUser(pk: number, changes: { name?: string; email?: string; groups?: string[] }): Promise<AuthentikUser> {
// Only what is to change, and never the user name: a PATCH leaves out everything it does not mention.
const body: Record<string, unknown> = {};
if (changes.name !== undefined) body.name = changes.name;
if (changes.email !== undefined) body.email = changes.email;
if (changes.groups !== undefined) body.groups = changes.groups.filter((g) => UUID.test(g));
const user = parseUser(await call("PATCH", `/core/users/${wholeNumber(pk)}/`, body));
if (!user) throw new AuthentikUserError("Authentik answered, but not with the user", "failed");
return user;
}
async function deleteUser(pk: number): Promise<void> { async function deleteUser(pk: number): Promise<void> {
await call("DELETE", `/core/users/${wholeNumber(pk)}/`); await call("DELETE", `/core/users/${wholeNumber(pk)}/`);
} }
@@ -248,5 +272,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return link; return link;
} }
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, deleteUser, listGroups, createUser, recoveryLink }); return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroups, createUser, recoveryLink });
} }
+67 -6
View File
@@ -6,7 +6,7 @@ import { authentikState, integrationCredentials, integrations } from "../db/sche
import { requireAuth, requireRole } from "../auth/middleware.js"; import { requireAuth, requireRole } from "../auth/middleware.js";
import { decryptSecret, encryptSecret } from "../crypto.js"; import { decryptSecret, encryptSecret } from "../crypto.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js"; import { applyGroupChange, AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
import { recordAudit } from "../services/audit.js"; import { recordAudit } from "../services/audit.js";
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js"; import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
import { asyncHandler } from "../utils/asyncHandler.js"; import { asyncHandler } from "../utils/asyncHandler.js";
@@ -61,13 +61,25 @@ function sendFailure(res: Response, err: unknown) {
const pkOf = (raw: string) => (/^\d{1,12}$/.test(raw) ? Number(raw) : Number.NaN); 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. */ type UserAction = "disable" | "enable" | "delete" | "edit";
async function guard(adapter: AuthentikUsersAdapter, pk: number, action: "disable" | "enable" | "delete"): Promise<{ user: AuthentikUser; refusal: string | null }> {
const user = await adapter.getUser(pk); /** 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. */
if (action === "enable" || isServiceAccount(user)) return { user, refusal: refusalFor(user, action, null, []) }; 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 self = await adapter.whoAmI();
const admins = user.admin && user.active ? await adapter.activeAdmins() : []; const admins = user.admin && user.active ? await adapter.activeAdmins() : [];
return { user, refusal: refusalFor(user, action, self, admins) }; 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({ const newUserSchema = z.object({
@@ -248,3 +260,52 @@ authentikRouter.delete("/:id/users/:pk", requireRole("admin"), asyncHandler(asyn
sendFailure(res, 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);
}
}));
+130 -6
View File
@@ -1,5 +1,5 @@
/** /**
* Looking after Authentik users: reading the list, switching a user off and on, deleting one — and what is refused (service accounts, the account the token belongs to, the last active * Looking after Authentik users: reading the list, switching a user off and on, editing one, deleting one — and what is refused (service accounts, the account the token belongs to, the last active
* administrator, a user name that does not match), who may, and what is written in the audit log. * administrator, a user name that does not match), who may, and what is written in the audit log.
* *
* Run with: npm test --workspace server * Run with: npm test --workspace server
@@ -36,12 +36,16 @@ interface FakeUser {
is_superuser: boolean; is_superuser: boolean;
last_login: string | null; last_login: string | null;
type: string; type: string;
groups?: string[];
} }
const person = (pk: number, username: string, extra: Partial<FakeUser> = {}): FakeUser => ({ pk, username, name: username.toUpperCase(), email: `${username}@example.com`, is_active: true, is_superuser: false, last_login: null, type: "internal", ...extra }); const G_ADMIN = "22222222-2222-4222-8222-222222222222";
const G_FAMILY = "11111111-1111-4111-8111-111111111111";
const G_OTHER = "44444444-4444-4444-8444-444444444444";
const person = (pk: number, username: string, extra: Partial<FakeUser> = {}): FakeUser => ({ pk, username, name: username.toUpperCase(), email: `${username}@example.com`, is_active: true, is_superuser: false, last_login: null, type: "internal", groups: [], ...extra });
const fresh = (): FakeUser[] => [ const fresh = (): FakeUser[] => [
person(1, "akadmin", { is_superuser: true, last_login: "2026-10-30T08:00:00Z" }), person(1, "akadmin", { is_superuser: true, last_login: "2026-10-30T08:00:00Z", groups: [G_ADMIN] }),
person(2, "bob", { is_superuser: true }), person(2, "bob", { is_superuser: true, groups: [G_ADMIN] }),
person(3, "carol"), person(3, "carol", { groups: [G_FAMILY] }),
person(4, "dave", { is_active: false }), person(4, "dave", { is_active: false }),
person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }), person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }),
]; ];
@@ -66,6 +70,18 @@ describe("what Authentik's answers are read as", () => {
assert.equal(usersApi.isServiceAccount({ type: "external" }), false); assert.equal(usersApi.isServiceAccount({ type: "external" }), false);
}); });
test("a user's groups are the ids Authentik gives; none given is not the same as none", () => {
assert.deepEqual(usersApi.parseUser({ pk: 3, username: "x", groups: [G_FAMILY, "nope", 7] })!.groups, [G_FAMILY]);
assert.deepEqual(usersApi.parseUser({ pk: 3, username: "x", groups: [] })!.groups, []);
assert.equal(usersApi.parseUser({ pk: 3, username: "x" })!.groups, null);
});
test("groups are changed from the ones there are now: what goes out goes, what comes in comes, once, and what neither mentions stays", () => {
assert.deepEqual(usersApi.applyGroupChange([G_FAMILY, G_OTHER], [G_ADMIN], [G_FAMILY]), [G_OTHER, G_ADMIN]);
assert.deepEqual(usersApi.applyGroupChange([G_FAMILY], [G_FAMILY], []), [G_FAMILY]);
assert.deepEqual(usersApi.applyGroupChange([G_FAMILY], [], [G_OTHER]), [G_FAMILY]);
});
test("who the token is comes out of /users/me/", () => { test("who the token is comes out of /users/me/", () => {
assert.equal(usersApi.parseMe({ user: { pk: 9 } }), 9); assert.equal(usersApi.parseMe({ user: { pk: 9 } }), 9);
assert.equal(usersApi.parseMe({ user: { pk: "9" } }), null); assert.equal(usersApi.parseMe({ user: { pk: "9" } }), null);
@@ -84,6 +100,12 @@ describe("what Authentik's answers are read as", () => {
assert.equal(usersApi.refusalFor({ ...bob, active: false }, "delete", 1, [1]), null, "one that is already off is not the one holding the door"); assert.equal(usersApi.refusalFor({ ...bob, active: false }, "delete", 1, [1]), null, "one that is already off is not the one holding the door");
assert.equal(usersApi.refusalFor(carol, "delete", 1, [1]), null); assert.equal(usersApi.refusalFor(carol, "delete", 1, [1]), null);
assert.equal(usersApi.refusalFor(dave, "disable", null, []), null); assert.equal(usersApi.refusalFor(dave, "disable", null, []), null);
// Editing: the token's own account and a service account never; the last administrator only when the edit would take them out of being one.
assert.match(usersApi.refusalFor(akadmin, "edit", 1, [1, 2]) ?? "", /token/);
assert.match(usersApi.refusalFor(outpost, "edit", 1, [1, 2]) ?? "", /service account/);
assert.match(usersApi.refusalFor(bob, "edit", 1, [2], true) ?? "", /only active administrator/);
assert.equal(usersApi.refusalFor(bob, "edit", 1, [2], false), null);
assert.equal(usersApi.refusalFor(bob, "edit", 1, [1, 2], true), null);
}); });
}); });
@@ -118,6 +140,7 @@ before(async () => {
res.end(JSON.stringify(json)); res.end(JSON.stringify(json));
}; };
const url = new URL(path, "http://x"); const url = new URL(path, "http://x");
if (req.method === "GET" && url.pathname === "/api/v3/core/groups/") return send(200, { results: [{ pk: G_ADMIN, name: "admins", is_superuser: true }, { pk: G_FAMILY, name: "Family", is_superuser: false }, { pk: G_OTHER, name: "Other", is_superuser: false }] });
if (req.method === "GET" && url.pathname === "/api/v3/core/users/me/") return send(200, { user: table.find((u) => u.pk === meId) ?? person(meId, "me") }); if (req.method === "GET" && url.pathname === "/api/v3/core/users/me/") return send(200, { user: table.find((u) => u.pk === meId) ?? person(meId, "me") });
if (req.method === "GET" && url.pathname === "/api/v3/core/users/") { if (req.method === "GET" && url.pathname === "/api/v3/core/users/") {
let list = table; let list = table;
@@ -134,7 +157,9 @@ before(async () => {
if (req.method === "GET") return send(200, user); if (req.method === "GET") return send(200, user);
if (req.method === "PATCH") { if (req.method === "PATCH") {
if (patchStatus !== 200) return send(patchStatus, { detail: "You do not have permission to perform this action." }); if (patchStatus !== 200) return send(patchStatus, { detail: "You do not have permission to perform this action." });
user.is_active = JSON.parse(body).is_active; const b = JSON.parse(body) as Partial<FakeUser>;
Object.assign(user, b);
if (b.groups) user.is_superuser = b.groups.includes(G_ADMIN);
return send(200, user); return send(200, user);
} }
if (req.method === "DELETE") { if (req.method === "DELETE") {
@@ -214,6 +239,7 @@ describe("the routes", () => {
const list = (sub = "admin", q = "") => fetch(`${base}/${id}/users${q}`, { headers: as(sub) }); const list = (sub = "admin", q = "") => fetch(`${base}/${id}/users${q}`, { headers: as(sub) });
const active = (pk: number, on: boolean, sub = "admin", integration = id) => fetch(`${base}/${integration}/users/${pk}/active`, { method: "POST", headers: as(sub), body: JSON.stringify({ active: on }) }); const active = (pk: number, on: boolean, sub = "admin", integration = id) => fetch(`${base}/${integration}/users/${pk}/active`, { method: "POST", headers: as(sub), body: JSON.stringify({ active: on }) });
const del = (pk: number, username: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ username }) }); const del = (pk: number, username: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ username }) });
const change = (pk: number, body: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) });
const writes = () => seen.filter((s) => s.method !== "GET"); const writes = () => seen.filter((s) => s.method !== "GET");
const reset = () => { const reset = () => {
table = fresh(); table = fresh();
@@ -347,6 +373,104 @@ describe("the routes", () => {
assert.equal((await audit("disable_authentik_user")).length, before, "nothing was done, so nothing more is written down"); assert.equal((await audit("disable_authentik_user")).length, before, "nothing was done, so nothing more is written down");
}); });
test("editing: only what differs is sent, never the user name; the audit log names the fields, not what they were changed to", async () => {
reset();
const res = await change(3, { name: "Carol C", email: "carol@new.example" });
assert.equal(res.status, 200);
assert.deepEqual(((await res.json()) as { changed: string[] }).changed, ["name", "email"]);
assert.deepEqual(writes().map((s) => [s.method, s.path, s.body]), [["PATCH", "/api/v3/core/users/3/", JSON.stringify({ name: "Carol C", email: "carol@new.example" })]]);
assert.deepEqual([table.find((u) => u.pk === 3)!.name, table.find((u) => u.pk === 3)!.username], ["Carol C", "carol"]);
const entry = (await audit("update_authentik_user")).at(-1)!;
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "3"]);
assert.match(entry.detail ?? "", /carol/);
assert.match(entry.detail ?? "", /"changed":\["name","email"\]/);
assert.equal(/new\.example|Carol C/.test(entry.detail ?? ""), false);
// The same again changes nothing, so nothing is sent and nothing is written down.
const before = (await audit("update_authentik_user")).length;
seen.length = 0;
const again = await change(3, { name: "Carol C", email: "carol@new.example", groupsAdd: [], groupsRemove: [] });
assert.deepEqual(((await again.json()) as { changed: string[] }).changed, []);
assert.deepEqual(writes(), []);
assert.equal((await audit("update_authentik_user")).length, before);
// An empty email clears it.
assert.equal((await change(3, { email: "" })).status, 200);
assert.equal(writes().at(-1)!.body, JSON.stringify({ email: "" }));
});
test("groups are changed by what goes in and out, on top of the groups the user has now", async () => {
reset();
// Somebody put carol in another group after the page was read: that stays.
table.find((u) => u.pk === 3)!.groups = [G_FAMILY, G_OTHER];
const res = await change(3, { groupsAdd: [G_ADMIN], groupsRemove: [G_FAMILY] });
assert.equal(res.status, 200);
assert.deepEqual(JSON.parse(writes()[0].body), { groups: [G_OTHER, G_ADMIN] });
seen.length = 0;
const same = await change(3, { groupsAdd: [G_OTHER], groupsRemove: [G_FAMILY] });
assert.deepEqual(((await same.json()) as { changed: string[] }).changed, [], "putting in what is there and taking out what is not changes nothing");
assert.deepEqual(writes(), []);
});
test("what is wrong with the change is said before Authentik is asked", async () => {
reset();
for (const bad of [{ name: "" }, { email: "not-an-email" }, { groupsAdd: ["not-a-uuid"] }, { groupsAdd: [G_FAMILY], groupsRemove: [G_FAMILY] }, { groupsRemove: "x" }]) {
const res = await change(3, bad);
assert.equal(res.status, 400, JSON.stringify(bad));
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
}
assert.equal((await fetch(`${base}/${id}/users/1e3`, { method: "PATCH", headers: as("admin"), body: JSON.stringify({ name: "x" }) })).status, 400);
assert.deepEqual(seen, []);
});
test("editing is refused for a service account, for the token's own account, and for the last administrator when it would take them out of being one", async () => {
reset();
const refused = async (res: Response, pattern: RegExp) => {
assert.equal(res.status, 409);
assert.match(((await res.json()) as { message: string }).message, pattern);
};
await refused(await change(5, { name: "x" }), /service account/);
await refused(await change(1, { name: "x" }), /token/);
assert.deepEqual(writes(), []);
// The token is carol's account now; bob is off, so akadmin is the only active administrator.
meId = 3;
table.find((u) => u.pk === 2)!.is_active = false;
await refused(await change(1, { groupsRemove: [G_ADMIN] }), /only active administrator/);
assert.deepEqual(writes(), []);
assert.equal((await change(1, { name: "Root" })).status, 200, "a name is no danger");
assert.equal((await change(1, { groupsAdd: [G_FAMILY] })).status, 200, "nor is another group");
assert.equal((await change(1, { groupsRemove: [G_FAMILY] })).status, 200);
// With another administrator on, they may be taken out of the group.
table.find((u) => u.pk === 2)!.is_active = true;
assert.equal((await change(1, { groupsRemove: [G_ADMIN] })).status, 200);
assert.deepEqual(table.find((u) => u.pk === 1)!.groups, []);
});
test("a user whose groups Authentik did not say can be renamed but not moved between groups", async () => {
reset();
delete table.find((u) => u.pk === 3)!.groups;
const res = await change(3, { groupsAdd: [G_FAMILY] });
assert.equal(res.status, 409);
assert.match(((await res.json()) as { message: string }).message, /did not say which groups/);
assert.deepEqual(writes(), []);
assert.equal((await change(3, { name: "Only Name" })).status, 200);
});
test("only an administrator edits; a user that is gone is not found; a token that may not is a bad gateway", async () => {
reset();
for (const sub of ["viewer", "operator"]) assert.equal((await change(3, { name: "x" }, sub)).status, 403, sub);
assert.deepEqual(seen, []);
assert.equal((await change(99, { name: "x" })).status, 404);
patchStatus = 403;
const res = await change(3, { name: "Someone Else" });
assert.equal(res.status, 502);
assert.match(((await res.json()) as { message: string }).message, /did not accept the token/);
});
test("the list carries each person's groups", async () => {
reset();
const body = (await (await list()).json()) as { users: { username: string; groups: string[] | null }[] };
assert.deepEqual(body.users.map((u) => [u.username, u.groups]), [["akadmin", [G_ADMIN]], ["bob", [G_ADMIN]], ["carol", [G_FAMILY]], ["dave", []]]);
});
test("an Authentik with no token for managing users is not asked anything", async () => { test("an Authentik with no token for managing users is not asked anything", async () => {
reset(); reset();
const res = await fetch(`${base}/${readOnly}/users`, { headers: as("admin") }); const res = await fetch(`${base}/${readOnly}/users`, { headers: as("admin") });
+3
View File
@@ -1781,6 +1781,8 @@ export interface AuthentikPerson {
/** May do everything in Authentik. */ /** May do everything in Authentik. */
admin: boolean; admin: boolean;
lastLogin: string | null; lastLogin: string | null;
/** Group ids; null when Authentik did not say, and then they are not changed from here. */
groups: string[] | null;
} }
/** A user Authentik made, and the one-time link for them to choose a password with (null, with the reason, when that could not be made). */ /** A user Authentik made, and the one-time link for them to choose a password with (null, with the reason, when that could not be made). */
@@ -3426,6 +3428,7 @@ export const api = {
createUser: (id: number, body: AuthentikNewUser) => request<AuthentikUserMade>(`/api/authentik/${id}/users`, { method: "POST", body: JSON.stringify(body) }), createUser: (id: number, body: AuthentikNewUser) => request<AuthentikUserMade>(`/api/authentik/${id}/users`, { method: "POST", body: JSON.stringify(body) }),
users: (id: number, search = "") => request<{ users: AuthentikPerson[]; more: boolean; self: number | null }>(`/api/authentik/${id}/users${search.trim() ? `?search=${encodeURIComponent(search.trim())}` : ""}`), users: (id: number, search = "") => request<{ users: AuthentikPerson[]; more: boolean; self: number | null }>(`/api/authentik/${id}/users${search.trim() ? `?search=${encodeURIComponent(search.trim())}` : ""}`),
setUserActive: (id: number, pk: number, active: boolean) => request<{ user: AuthentikPerson }>(`/api/authentik/${id}/users/${pk}/active`, { method: "POST", body: JSON.stringify({ active }) }), setUserActive: (id: number, pk: number, active: boolean) => request<{ user: AuthentikPerson }>(`/api/authentik/${id}/users/${pk}/active`, { method: "POST", body: JSON.stringify({ active }) }),
updateUser: (id: number, pk: number, body: { name?: string; email?: string; groupsAdd?: string[]; groupsRemove?: string[] }) => request<{ user: AuthentikPerson; changed: string[] }>(`/api/authentik/${id}/users/${pk}`, { method: "PATCH", body: JSON.stringify(body) }),
deleteUser: (id: number, pk: number, username: string) => request<void>(`/api/authentik/${id}/users/${pk}`, { method: "DELETE", body: JSON.stringify({ username }) }), deleteUser: (id: number, pk: number, username: string) => request<void>(`/api/authentik/${id}/users/${pk}`, { method: "DELETE", body: JSON.stringify({ username }) }),
removeWriteToken: (id: number) => request<void>(`/api/authentik/${id}/write-token`, { method: "DELETE" }), removeWriteToken: (id: number) => request<void>(`/api/authentik/${id}/write-token`, { method: "DELETE" }),
}, },
+87
View File
@@ -0,0 +1,87 @@
import { useState, type FormEvent } from "react";
import type { AuthentikGroup, AuthentikPerson } from "../api/client";
export interface AuthentikChange {
name?: string;
email?: string;
groupsAdd?: string[];
groupsRemove?: string[];
}
/**
* The form for changing what a person is called, their email and the groups they belong to. The user name is shown and can't be changed here: it is how the person is known elsewhere.
* Groups are sent as what goes in and what comes out, not as a list, so a group somebody else gave them meanwhile is not lost.
*/
export default function AuthentikEditUser({ p, groups, groupsError, busy, onSave, onCancel }: { p: AuthentikPerson; groups: AuthentikGroup[] | null; groupsError: string | null; busy: boolean; onSave: (change: AuthentikChange) => void; onCancel: () => void }) {
const [name, setName] = useState(p.name);
const [email, setEmail] = useState(p.email ?? "");
const [picked, setPicked] = useState<string[]>(p.groups ?? []);
const canEditGroups = p.groups !== null && groups !== null && !groupsError;
const toggle = (id: string) => setPicked((cur) => (cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]));
function submit(e: FormEvent) {
e.preventDefault();
const change: AuthentikChange = {};
if (name.trim() !== p.name) change.name = name.trim();
if (email.trim() !== (p.email ?? "")) change.email = email.trim();
if (canEditGroups && p.groups) {
const add = picked.filter((g) => !p.groups!.includes(g));
const remove = p.groups.filter((g) => !picked.includes(g) && groups!.some((x) => x.id === g));
if (add.length > 0) change.groupsAdd = add;
if (remove.length > 0) change.groupsRemove = remove;
}
if (Object.keys(change).length === 0) return onCancel();
onSave(change);
}
return (
<form onSubmit={submit} className="p-2">
<div className="text-secondary small mb-2">
User name: <strong>{p.username}</strong> — it can&rsquo;t be changed here, it is how they are known elsewhere.
</div>
<div className="row g-2 mb-3">
<div className="col-md-6">
<label className="form-label" htmlFor={`ak-edit-name-${p.pk}`}>
Name
</label>
<input id={`ak-edit-name-${p.pk}`} className="form-control form-control-sm" required maxLength={200} autoComplete="off" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="col-md-6">
<label className="form-label" htmlFor={`ak-edit-email-${p.pk}`}>
Email <span className="text-secondary">(empty to clear)</span>
</label>
<input id={`ak-edit-email-${p.pk}`} type="email" className="form-control form-control-sm" maxLength={254} autoComplete="off" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
</div>
<div className="form-label">Groups</div>
{p.groups === null && <div className="text-secondary small mb-3">Authentik did not say which groups this user is in, so only the name and email can be changed here.</div>}
{p.groups !== null && groupsError && <div className="text-yellow small mb-3">The groups could not be read: {groupsError}. The name and email can still be changed.</div>}
{p.groups !== null && !groupsError && groups === null && <div className="text-secondary small mb-3">Reading the groups…</div>}
{canEditGroups && groups!.length === 0 && <div className="text-secondary small mb-3">There are no groups.</div>}
{canEditGroups && groups!.length > 0 && (
<div className="mb-3">
{groups!.map((g) => (
<label key={g.id} className="form-check">
<input type="checkbox" className="form-check-input" checked={picked.includes(g.id)} onChange={() => toggle(g.id)} />
<span className="form-check-label">
{g.name}
{g.admin && <span className="badge bg-yellow-lt text-yellow ms-2">administrators</span>}
</span>
</label>
))}
</div>
)}
<div className="d-flex gap-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>
);
}
+45 -4
View File
@@ -1,12 +1,13 @@
import { useState, type FormEvent } from "react"; import { useState, type FormEvent } from "react";
import { api, type AuthentikInfo, type AuthentikPerson } from "../api/client"; import { api, type AuthentikGroup, type AuthentikInfo, type AuthentikPerson } from "../api/client";
import AuthentikEditUser, { type AuthentikChange } from "./AuthentikEditUser";
import TimeAgo from "./TimeAgo"; import TimeAgo from "./TimeAgo";
import { ErrorNotice } from "./Notice"; import { ErrorNotice } from "./Notice";
import { confirmDialog, promptDialog } from "../utils/dialogs"; import { confirmDialog, promptDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors"; import { readableError } from "../utils/errors";
/** /**
* The people in an Authentik, for an administrator to switch off, switch on again or delete. Switching off is the way that can be undone; deleting asks for the user name to be typed. * The people in an Authentik, for an administrator to edit, switch off, switch on again or delete. Switching off is the way that can be undone; deleting asks for the user name to be typed.
* The account the token belongs to has no buttons, and neither does the last active administrator: the server refuses them too, and says why. * The account the token belongs to has no buttons, and neither does the last active administrator: the server refuses them too, and says why.
*/ */
export default function AuthentikUserList({ a }: { a: AuthentikInfo }) { export default function AuthentikUserList({ a }: { a: AuthentikInfo }) {
@@ -16,9 +17,38 @@ export default function AuthentikUserList({ a }: { a: AuthentikInfo }) {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [busy, setBusy] = useState<number | "list" | null>(null); const [busy, setBusy] = useState<number | "list" | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<number | null>(null);
const [groups, setGroups] = useState<AuthentikGroup[] | null>(null);
const [groupsError, setGroupsError] = useState<string | null>(null);
if (!a.canCreateUsers) return null; if (!a.canCreateUsers) return null;
async function startEdit(p: AuthentikPerson) {
setEditing(p.pk);
setError(null);
if (groups !== null) return;
try {
setGroups((await api.authentik.groups(a.id)).groups);
setGroupsError(null);
} catch (err) {
setGroups([]);
setGroupsError(readableError(err));
}
}
async function save(p: AuthentikPerson, change: AuthentikChange) {
setBusy(p.pk);
setError(null);
try {
await api.authentik.updateUser(a.id, p.pk, change);
setEditing(null);
await load();
} catch (err) {
setError(readableError(err));
setBusy(null);
}
}
async function load(q = search) { async function load(q = search) {
setBusy("list"); setBusy("list");
setError(null); setError(null);
@@ -114,7 +144,14 @@ export default function AuthentikUserList({ a }: { a: AuthentikInfo }) {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{people.map((p) => ( {people.map((p) =>
editing === p.pk ? (
<tr key={p.pk}>
<td colSpan={4}>
<AuthentikEditUser p={p} groups={groups} groupsError={groupsError} busy={busy === p.pk} onSave={(change) => void save(p, change)} onCancel={() => setEditing(null)} />
</td>
</tr>
) : (
<tr key={p.pk} className={p.active ? "" : "text-secondary"}> <tr key={p.pk} className={p.active ? "" : "text-secondary"}>
<td> <td>
{p.username} {p.username}
@@ -133,6 +170,9 @@ export default function AuthentikUserList({ a }: { a: AuthentikInfo }) {
</span> </span>
) : ( ) : (
<> <>
<button type="button" className="btn btn-sm btn-outline-secondary me-1" disabled={busy !== null} onClick={() => void startEdit(p)}>
Edit
</button>
<button type="button" className="btn btn-sm btn-outline-secondary me-1" disabled={busy !== null} onClick={() => void switchTo(p, !p.active)}> <button type="button" className="btn btn-sm btn-outline-secondary me-1" disabled={busy !== null} onClick={() => void switchTo(p, !p.active)}>
{p.active ? "Switch off" : "Switch on"} {p.active ? "Switch off" : "Switch on"}
</button> </button>
@@ -143,7 +183,8 @@ export default function AuthentikUserList({ a }: { a: AuthentikInfo }) {
)} )}
</td> </td>
</tr> </tr>
))} ),
)}
</tbody> </tbody>
</table> </table>
</div> </div>