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
+7
-3
@@ -518,14 +518,18 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
|
|||||||
|
|
||||||
### Authentik
|
### Authentik
|
||||||
|
|
||||||
- **Config fields:** the **address** of Authentik (`https://auth.example.lan`), an **API token** (Authentik → Directory → Tokens and App passwords → *Create*, intent **API Token**, for a user who may read; stored encrypted), optionally a **token for making users** (below) and, for an https address with a certificate you made yourself, *insecure*.
|
- **Config fields:** the **address** of Authentik (`https://auth.example.lan`), an **API token** (Authentik → Directory → Tokens and App passwords → *Create*, intent **API Token**, for a user who may read; stored encrypted), optionally a **token for making and managing users** (below) and, for an https address with a certificate you made yourself, *insecure*.
|
||||||
- **Required access:** read only. This app only ever sends GET requests: the version, the workers, the outposts and their health, the certificates, the tokens and the events log. **Nothing is ever changed.** Give the token a user with just enough to read these (an administrator, or a user in a role that may view them);
|
- **Required access:** read only. This app only ever sends GET requests: the version, the workers, the outposts and their health, the certificates, the tokens and the events log. **Nothing is ever changed.** Give the token a user with just enough to read these (an administrator, or a user in a role that may view them);
|
||||||
if one of the lists is refused, that part is left out and the rest still works.
|
if one of the lists is refused, that part is left out and the rest still works.
|
||||||
- **Making a user (optional, administrators only):** with a second, separate token in *Token for making users* — an API token of an account that may add users, which is close to an administrator of Authentik, so give it only if you want this — **Apps → Authentik → New user** makes a user
|
- **Making and managing users (optional, administrators only):** with a second, separate token in *Token for making and managing users* — an API token of an account that may add, change and delete users, which is close to an administrator of Authentik, so give it only if you want this — **Apps → Authentik → New user** makes a user
|
||||||
(user name, name, an email if there is one, and groups, which are read from Authentik when the form opens; a group that makes members administrators of Authentik is marked) and then a **one-time recovery link** for them. They open the link and **choose their own password**: this app never sets, sees or keeps one.
|
(user name, name, an email if there is one, and groups, which are read from Authentik when the form opens; a group that makes members administrators of Authentik is marked) and then a **one-time recovery link** for them. They open the link and **choose their own password**: this app never sets, sees or keeps one.
|
||||||
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). 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/`, asking for a link that lasts a day, which a version of
|
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;
|
||||||
|
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
|
||||||
|
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
|
||||||
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.
|
||||||
|
|||||||
@@ -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.
|
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.
|
||||||
|
|
||||||
**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.
|
||||||
|
|||||||
@@ -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) is an administrator's alone, and only for an Authentik that was given a token for it; it is written in the audit log (who made 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 **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.
|
||||||
- **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.
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
/**
|
/**
|
||||||
* Making a user in Authentik: the one thing this app does there that is not reading. It is kept apart from the adapter that reads (./adapter.ts, which sends nothing but GET requests with
|
* Making and looking after users in Authentik: what this app does there that is not reading. It is kept apart from the adapter that reads (./adapter.ts, which sends nothing but GET requests with
|
||||||
* the integration's own token) and it has a token of its own — `writeToken`, optional, from an account that may add users — so an Authentik that is only watched is never written to.
|
* the integration's own token) and it has a token of its own — `writeToken`, optional, from an account that may add, change and delete users — so an Authentik that is only watched is never written to.
|
||||||
*
|
*
|
||||||
* 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
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
* 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
|
||||||
* the address it was asked at, so it is only as good as the address in the integration.
|
* the address it was asked at, so it is only as good as the address in the integration.
|
||||||
*/
|
*/
|
||||||
@@ -39,9 +43,9 @@ export interface CreatedAuthentikUser {
|
|||||||
name: string;
|
name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How a call failed: `invalid` — Authentik looked at it and said no (a name taken, a bad address); `denied` — the token is not accepted or may not; `failed` — no answer, or one that makes no sense. */
|
/** How a call failed: `invalid` — Authentik looked at it and said no (a name taken, a bad address); `denied` — the token is not accepted or may not; `missing` — there is no such thing there (a user that is gone); `failed` — no answer, or one that makes no sense. */
|
||||||
export class AuthentikUserError extends Error {
|
export class AuthentikUserError extends Error {
|
||||||
constructor(message: string, readonly kind: "invalid" | "denied" | "failed") {
|
constructor(message: string, readonly kind: "invalid" | "denied" | "missing" | "failed") {
|
||||||
super(message);
|
super(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,6 +55,10 @@ const PAGE = 200;
|
|||||||
|
|
||||||
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
|
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
|
||||||
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
|
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
|
||||||
|
const iso = (v: unknown): string | null => {
|
||||||
|
const s = str(v);
|
||||||
|
return s && Number.isFinite(Date.parse(s)) ? new Date(s).toISOString() : null;
|
||||||
|
};
|
||||||
|
|
||||||
/** Pure: the groups of a `/core/groups/` page, by name. */
|
/** Pure: the groups of a `/core/groups/` page, by name. */
|
||||||
export function parseGroups(raw: unknown): AuthentikGroup[] {
|
export function parseGroups(raw: unknown): AuthentikGroup[] {
|
||||||
@@ -87,6 +95,57 @@ export function parseRecoveryLink(raw: unknown): string | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A user as the list shows them. */
|
||||||
|
export interface AuthentikUser {
|
||||||
|
pk: number;
|
||||||
|
username: string;
|
||||||
|
name: string;
|
||||||
|
email: string | null;
|
||||||
|
active: boolean;
|
||||||
|
/** A member of a superuser group, or a superuser themselves: may do everything in Authentik. */
|
||||||
|
admin: boolean;
|
||||||
|
lastLogin: string | null;
|
||||||
|
/** internal, external, service_account, internal_service_account. */
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What an outpost or an integration signs in with: not a person, and not this app's to switch off or delete. */
|
||||||
|
export const isServiceAccount = (u: Pick<AuthentikUser, "type">): boolean => u.type === "service_account" || u.type === "internal_service_account";
|
||||||
|
|
||||||
|
/** Pure: one user; null when the answer is not a user. A version that does not say what type a user is has only people. */
|
||||||
|
export function parseUser(raw: unknown): AuthentikUser | null {
|
||||||
|
const u = obj(raw);
|
||||||
|
const pk = typeof u.pk === "number" ? u.pk : Number.NaN;
|
||||||
|
const username = str(u.username);
|
||||||
|
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" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pure: the people of a `/core/users/` page (service accounts left out), and whether there are more pages than this one. */
|
||||||
|
export function parseUsers(raw: unknown): { users: AuthentikUser[]; more: boolean } {
|
||||||
|
const list = Array.isArray(raw) ? raw : Array.isArray(obj(raw).results) ? (obj(raw).results as unknown[]) : [];
|
||||||
|
const users = list.map(parseUser).filter((u): u is AuthentikUser => u !== null && !isServiceAccount(u));
|
||||||
|
return { users, more: Number(obj(obj(raw).pagination).total_pages) > 1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pure: which user the token is, out of `/core/users/me/`; null when it does not say. */
|
||||||
|
export function parseMe(raw: unknown): number | null {
|
||||||
|
const pk = obj(obj(raw).user).pk;
|
||||||
|
return typeof pk === "number" && Number.isInteger(pk) && pk > 0 ? pk : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* 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).
|
||||||
|
*/
|
||||||
|
export function refusalFor(user: AuthentikUser, action: "disable" | "enable" | "delete", self: number | null, activeAdmins: number[]): 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 (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 (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.";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Pure: what Authentik's complaint says, in words. It answers `{"username": ["…"]}`, `{"detail": "…"}` or `{"non_field_errors": ["…"]}`; the longest it is allowed to be is a sentence or two. */
|
/** Pure: what Authentik's complaint says, in words. It answers `{"username": ["…"]}`, `{"detail": "…"}` or `{"non_field_errors": ["…"]}`; the longest it is allowed to be is a sentence or two. */
|
||||||
export function describeComplaint(raw: unknown): string | null {
|
export function describeComplaint(raw: unknown): string | null {
|
||||||
const o = obj(raw);
|
const o = obj(raw);
|
||||||
@@ -100,6 +159,14 @@ export function describeComplaint(raw: unknown): string | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthentikUsersAdapter {
|
export interface AuthentikUsersAdapter {
|
||||||
|
listUsers(search?: string): Promise<{ users: AuthentikUser[]; more: boolean }>;
|
||||||
|
getUser(pk: number): Promise<AuthentikUser>;
|
||||||
|
/** The user the token belongs to. */
|
||||||
|
whoAmI(): Promise<number | null>;
|
||||||
|
/** The pks of the active administrators (people), enough of them to tell whether there is more than one. */
|
||||||
|
activeAdmins(): Promise<number[]>;
|
||||||
|
setActive(pk: number, active: boolean): Promise<AuthentikUser>;
|
||||||
|
deleteUser(pk: number): Promise<void>;
|
||||||
listGroups(): Promise<AuthentikGroup[]>;
|
listGroups(): Promise<AuthentikGroup[]>;
|
||||||
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
|
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
|
||||||
recoveryLink(pk: number): Promise<string>;
|
recoveryLink(pk: number): Promise<string>;
|
||||||
@@ -110,7 +177,7 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
|||||||
const insecure = config.insecure === true;
|
const insecure = config.insecure === true;
|
||||||
const headers = { Authorization: `Bearer ${config.writeToken ?? ""}`, Accept: "application/json" };
|
const headers = { Authorization: `Bearer ${config.writeToken ?? ""}`, Accept: "application/json" };
|
||||||
|
|
||||||
async function call(method: "GET" | "POST", path: string, body?: unknown): Promise<unknown> {
|
async function call(method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown): Promise<unknown> {
|
||||||
let res;
|
let res;
|
||||||
try {
|
try {
|
||||||
res = await requestJson(`${base}/api/v3${path}`, { method, headers, body, insecure });
|
res = await requestJson(`${base}/api/v3${path}`, { method, headers, body, insecure });
|
||||||
@@ -118,13 +185,49 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
|||||||
throw new AuthentikUserError(`Authentik could not be reached: ${err instanceof Error ? err.message : String(err)}`, "failed");
|
throw new AuthentikUserError(`Authentik could not be reached: ${err instanceof Error ? err.message : String(err)}`, "failed");
|
||||||
}
|
}
|
||||||
if (res.status === 401 || res.status === 403) throw new AuthentikUserError(`Authentik did not accept the token for making users (HTTP ${res.status}) — it must be an API token of an account that may add users`, "denied");
|
if (res.status === 401 || res.status === 403) throw new AuthentikUserError(`Authentik did not accept the token for making users (HTTP ${res.status}) — it must be an API token of an account that may add users`, "denied");
|
||||||
if (res.status === 404) throw new AuthentikUserError("Authentik has no API at this address, or no such thing there — check the address", "failed");
|
if (res.status === 404) throw new AuthentikUserError("Authentik has no such thing there — a user that is gone, or an address that is not Authentik's", "missing");
|
||||||
if (res.status === 400) throw new AuthentikUserError(describeComplaint(res.json) ?? "Authentik did not accept that", "invalid");
|
if (res.status === 400) throw new AuthentikUserError(describeComplaint(res.json) ?? "Authentik did not accept that", "invalid");
|
||||||
if (res.status < 200 || res.status >= 300) throw new AuthentikUserError(`Authentik error: HTTP ${res.status}`, "failed");
|
if (res.status < 200 || res.status >= 300) throw new AuthentikUserError(`Authentik error: HTTP ${res.status}`, "failed");
|
||||||
if (res.json === null) throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "failed");
|
// A delete is answered with nothing; everything else with JSON.
|
||||||
|
if (res.json === null && method !== "DELETE") throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "failed");
|
||||||
return res.json;
|
return res.json;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const wholeNumber = (pk: number) => {
|
||||||
|
if (!Number.isInteger(pk) || pk <= 0) throw new AuthentikUserError("That is not a user id", "invalid");
|
||||||
|
return pk;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function listUsers(search?: string) {
|
||||||
|
const q = search?.trim() ? `&search=${encodeURIComponent(search.trim())}` : "";
|
||||||
|
return parseUsers(await call("GET", `/core/users/?page_size=${PAGE}&ordering=username${q}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getUser(pk: number): Promise<AuthentikUser> {
|
||||||
|
const user = parseUser(await call("GET", `/core/users/${wholeNumber(pk)}/`));
|
||||||
|
if (!user) throw new AuthentikUserError("Authentik answered, but not with a user", "failed");
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function whoAmI(): Promise<number | null> {
|
||||||
|
return parseMe(await call("GET", "/core/users/me/"));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function activeAdmins(): Promise<number[]> {
|
||||||
|
return parseUsers(await call("GET", "/core/users/?is_superuser=true&is_active=true&page_size=3")).users.map((u) => u.pk);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setActive(pk: number, active: boolean): Promise<AuthentikUser> {
|
||||||
|
// Only that one field: nothing else about the user is sent, so nothing else can change.
|
||||||
|
const user = parseUser(await call("PATCH", `/core/users/${wholeNumber(pk)}/`, { is_active: active }));
|
||||||
|
if (!user) throw new AuthentikUserError("Authentik answered, but not with the user", "failed");
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteUser(pk: number): Promise<void> {
|
||||||
|
await call("DELETE", `/core/users/${wholeNumber(pk)}/`);
|
||||||
|
}
|
||||||
|
|
||||||
async function listGroups(): Promise<AuthentikGroup[]> {
|
async function listGroups(): Promise<AuthentikGroup[]> {
|
||||||
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name`));
|
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name`));
|
||||||
}
|
}
|
||||||
@@ -145,5 +248,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
|||||||
return link;
|
return link;
|
||||||
}
|
}
|
||||||
|
|
||||||
return withDiagLogging("authentik", { listGroups, createUser, recoveryLink });
|
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, deleteUser, listGroups, createUser, recoveryLink });
|
||||||
}
|
}
|
||||||
@@ -187,7 +187,7 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
|
|||||||
authentik: [
|
authentik: [
|
||||||
{ key: "url", label: "Authentik URL", secret: false, placeholder: "https://auth.example.lan" },
|
{ key: "url", label: "Authentik URL", secret: false, placeholder: "https://auth.example.lan" },
|
||||||
{ key: "token", label: "API token", secret: true, type: "password", placeholder: "Directory → Tokens and App passwords, intent API Token" },
|
{ key: "token", label: "API token", secret: true, type: "password", placeholder: "Directory → Tokens and App passwords, intent API Token" },
|
||||||
{ key: "writeToken", label: "Token for making users (optional)", secret: true, optional: true, type: "password", placeholder: "only to make users from here; an account that may add users. Leave blank to only watch" },
|
{ key: "writeToken", label: "Token for making and managing users (optional)", secret: true, optional: true, type: "password", placeholder: "only to make, switch off and delete users from here; an account that may. Leave blank to only watch" },
|
||||||
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
||||||
],
|
],
|
||||||
jellyfin: [
|
jellyfin: [
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export interface JsonResponse {
|
|||||||
|
|
||||||
const TIMEOUT_MS = 15_000;
|
const TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
export function requestJson(url: string, opts: { method?: "GET" | "POST"; headers?: Record<string, string>; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise<JsonResponse> {
|
export function requestJson(url: string, opts: { method?: "GET" | "POST" | "PATCH" | "DELETE"; headers?: Record<string, string>; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise<JsonResponse> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let parsed: URL;
|
let parsed: URL;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -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, 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 { 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";
|
||||||
@@ -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. */
|
/** 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) {
|
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) });
|
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({
|
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."),
|
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),
|
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();
|
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);
|
||||||
|
}
|
||||||
|
}));
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* administrator, a user name that does not match), who may, and what is written in the audit log.
|
||||||
|
*
|
||||||
|
* Run with: npm test --workspace server
|
||||||
|
*/
|
||||||
|
import { test, describe, before, after } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { createServer as createHttpServer, type Server } from "node:http";
|
||||||
|
import { mkdtempSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { AddressInfo } from "node:net";
|
||||||
|
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "hm-authentik-useradmin-"));
|
||||||
|
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||||
|
process.env.SESSION_DIR = join(dir, "sessions");
|
||||||
|
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||||
|
|
||||||
|
const express = (await import("express")).default;
|
||||||
|
const { db } = await import("../src/db/client.js");
|
||||||
|
const { users, integrations, integrationCredentials, auditLog } = await import("../src/db/schema.js");
|
||||||
|
const { runMigrations } = await import("../src/db/migrate.js");
|
||||||
|
const { encryptSecret } = await import("../src/crypto.js");
|
||||||
|
const usersApi = await import("../src/integrations/authentik/users.js");
|
||||||
|
const { authentikRouter } = await import("../src/routes/authentik.js");
|
||||||
|
|
||||||
|
await runMigrations();
|
||||||
|
|
||||||
|
interface FakeUser {
|
||||||
|
pk: number;
|
||||||
|
username: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
is_active: boolean;
|
||||||
|
is_superuser: boolean;
|
||||||
|
last_login: string | null;
|
||||||
|
type: 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 fresh = (): FakeUser[] => [
|
||||||
|
person(1, "akadmin", { is_superuser: true, last_login: "2026-10-30T08:00:00Z" }),
|
||||||
|
person(2, "bob", { is_superuser: true }),
|
||||||
|
person(3, "carol"),
|
||||||
|
person(4, "dave", { is_active: false }),
|
||||||
|
person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }),
|
||||||
|
];
|
||||||
|
|
||||||
|
describe("what Authentik's answers are read as", () => {
|
||||||
|
test("the list: people only, with whether they are on, administrators and when they last signed in; and whether there are more pages", () => {
|
||||||
|
const { users: list, more } = usersApi.parseUsers({ pagination: { total_pages: 2 }, results: fresh() });
|
||||||
|
assert.deepEqual(list.map((u) => u.username), ["akadmin", "bob", "carol", "dave"], "the outpost's account is not a person");
|
||||||
|
assert.deepEqual([list[0].admin, list[0].lastLogin, list[3].active, list[2].email], [true, "2026-10-30T08:00:00.000Z", false, "carol@example.com"]);
|
||||||
|
assert.equal(more, true);
|
||||||
|
assert.equal(usersApi.parseUsers({ pagination: { total_pages: 1 }, results: [] }).more, false);
|
||||||
|
assert.deepEqual(usersApi.parseUsers("nonsense"), { users: [], more: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a user needs a whole-number id and a user name; a version that does not say the type has only people", () => {
|
||||||
|
assert.equal(usersApi.parseUser({ pk: "3", username: "x" }), null);
|
||||||
|
assert.equal(usersApi.parseUser({ pk: 3 }), null);
|
||||||
|
const u = usersApi.parseUser({ pk: 3, username: "x" })!;
|
||||||
|
assert.deepEqual([u.type, u.active, u.admin, u.email, u.name], ["internal", true, false, null, "x"]);
|
||||||
|
assert.equal(usersApi.isServiceAccount({ type: "service_account" }), true);
|
||||||
|
assert.equal(usersApi.isServiceAccount({ type: "internal_service_account" }), true);
|
||||||
|
assert.equal(usersApi.isServiceAccount({ type: "external" }), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
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" } }), null);
|
||||||
|
assert.equal(usersApi.parseMe({}), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("what is refused: a service account always; the token's own account and the last active administrator when switching off or deleting; switching on, never", () => {
|
||||||
|
const [akadmin, bob, carol, dave, outpost] = fresh().map((f) => usersApi.parseUser(f)!);
|
||||||
|
assert.match(usersApi.refusalFor(outpost, "disable", 1, [1, 2]) ?? "", /service account/);
|
||||||
|
assert.match(usersApi.refusalFor(outpost, "enable", 1, [1, 2]) ?? "", /service account/);
|
||||||
|
assert.match(usersApi.refusalFor(akadmin, "disable", 1, [1, 2]) ?? "", /token/);
|
||||||
|
assert.match(usersApi.refusalFor(akadmin, "delete", 1, [1, 2]) ?? "", /token/);
|
||||||
|
assert.equal(usersApi.refusalFor(akadmin, "enable", 1, [1, 2]), null);
|
||||||
|
assert.equal(usersApi.refusalFor(bob, "disable", 1, [1, 2]), null, "there is another administrator");
|
||||||
|
assert.match(usersApi.refusalFor(bob, "delete", 1, [2]) ?? "", /only active administrator/);
|
||||||
|
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(dave, "disable", null, []), null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** An Authentik with a few users that remembers what it was asked. */
|
||||||
|
interface Seen {
|
||||||
|
method: string;
|
||||||
|
path: string;
|
||||||
|
auth: string;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
const seen: Seen[] = [];
|
||||||
|
let table = fresh();
|
||||||
|
let meId = 1;
|
||||||
|
let patchStatus = 200;
|
||||||
|
|
||||||
|
let fake: Server;
|
||||||
|
let fakeUrl = "";
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
fake = createHttpServer((req, res) => {
|
||||||
|
let body = "";
|
||||||
|
req.on("data", (c) => (body += c));
|
||||||
|
req.on("end", () => {
|
||||||
|
const path = req.url ?? "";
|
||||||
|
seen.push({ method: req.method ?? "", path, auth: String(req.headers.authorization ?? ""), body });
|
||||||
|
const send = (status: number, json?: unknown) => {
|
||||||
|
if (json === undefined) {
|
||||||
|
res.writeHead(status);
|
||||||
|
return res.end();
|
||||||
|
}
|
||||||
|
res.writeHead(status, { "content-type": "application/json" });
|
||||||
|
res.end(JSON.stringify(json));
|
||||||
|
};
|
||||||
|
const url = new URL(path, "http://x");
|
||||||
|
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/") {
|
||||||
|
let list = table;
|
||||||
|
if (url.searchParams.get("is_superuser") === "true") list = list.filter((u) => u.is_superuser);
|
||||||
|
if (url.searchParams.get("is_active") === "true") list = list.filter((u) => u.is_active);
|
||||||
|
const q = url.searchParams.get("search");
|
||||||
|
if (q) list = list.filter((u) => u.username.includes(q) || u.name.toLowerCase().includes(q.toLowerCase()));
|
||||||
|
return send(200, { pagination: { total_pages: 1 }, results: list });
|
||||||
|
}
|
||||||
|
const one = /^\/api\/v3\/core\/users\/(\d+)\/$/.exec(url.pathname);
|
||||||
|
if (one) {
|
||||||
|
const user = table.find((u) => u.pk === Number(one[1]));
|
||||||
|
if (!user) return send(404, { detail: "Not found." });
|
||||||
|
if (req.method === "GET") return send(200, user);
|
||||||
|
if (req.method === "PATCH") {
|
||||||
|
if (patchStatus !== 200) return send(patchStatus, { detail: "You do not have permission to perform this action." });
|
||||||
|
user.is_active = JSON.parse(body).is_active;
|
||||||
|
return send(200, user);
|
||||||
|
}
|
||||||
|
if (req.method === "DELETE") {
|
||||||
|
table = table.filter((u) => u.pk !== user.pk);
|
||||||
|
return send(204);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return send(200, { results: [] });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise<void>((resolve) => fake.listen(0, "127.0.0.1", resolve));
|
||||||
|
fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`;
|
||||||
|
});
|
||||||
|
after(() => {
|
||||||
|
fake.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the calls", () => {
|
||||||
|
const adapter = () => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken: "write-tok" });
|
||||||
|
const reset = () => {
|
||||||
|
table = fresh();
|
||||||
|
meId = 1;
|
||||||
|
patchStatus = 200;
|
||||||
|
seen.length = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
test("the list is asked for by name, with what was searched for, using the token for managing users", async () => {
|
||||||
|
reset();
|
||||||
|
const all = await adapter().listUsers();
|
||||||
|
assert.deepEqual(all.users.map((u) => u.username), ["akadmin", "bob", "carol", "dave"]);
|
||||||
|
const found = await adapter().listUsers(" car ol&x ");
|
||||||
|
assert.deepEqual(found.users, [], "nothing is called that");
|
||||||
|
assert.match(seen[1].path, /search=car%20ol%26x$/);
|
||||||
|
assert.deepEqual([...new Set(seen.map((s) => s.auth))], ["Bearer write-tok"]);
|
||||||
|
assert.equal(await adapter().whoAmI(), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("switching off is a PATCH of that one field and nothing else; deleting is a DELETE of that user", async () => {
|
||||||
|
reset();
|
||||||
|
const off = await adapter().setActive(3, false);
|
||||||
|
assert.equal(off.active, false);
|
||||||
|
assert.deepEqual([seen[0].method, seen[0].path, seen[0].body], ["PATCH", "/api/v3/core/users/3/", JSON.stringify({ is_active: false })]);
|
||||||
|
await adapter().deleteUser(4);
|
||||||
|
assert.deepEqual([seen[1].method, seen[1].path], ["DELETE", "/api/v3/core/users/4/"]);
|
||||||
|
assert.equal(table.some((u) => u.pk === 4), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a user id that is not a whole number is never put in the address; a user that is gone is said so", async () => {
|
||||||
|
reset();
|
||||||
|
for (const bad of [0, -1, 1.5, Number.NaN]) {
|
||||||
|
await assert.rejects(() => adapter().setActive(bad, false), /not a user id/);
|
||||||
|
await assert.rejects(() => adapter().deleteUser(bad), /not a user id/);
|
||||||
|
await assert.rejects(() => adapter().getUser(bad), /not a user id/);
|
||||||
|
}
|
||||||
|
assert.deepEqual(seen, []);
|
||||||
|
await assert.rejects(
|
||||||
|
() => adapter().getUser(99),
|
||||||
|
(err: Error & { kind?: string }) => err.kind === "missing",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the active administrators are asked for as such", async () => {
|
||||||
|
reset();
|
||||||
|
assert.deepEqual(await adapter().activeAdmins(), [1, 2]);
|
||||||
|
assert.match(seen[0].path, /is_superuser=true/);
|
||||||
|
assert.match(seen[0].path, /is_active=true/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the routes", () => {
|
||||||
|
let app: Server;
|
||||||
|
let base = "";
|
||||||
|
let id = 0;
|
||||||
|
let readOnly = 0;
|
||||||
|
|
||||||
|
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": 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 del = (pk: number, username: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ username }) });
|
||||||
|
const writes = () => seen.filter((s) => s.method !== "GET");
|
||||||
|
const reset = () => {
|
||||||
|
table = fresh();
|
||||||
|
meId = 1;
|
||||||
|
patchStatus = 200;
|
||||||
|
seen.length = 0;
|
||||||
|
};
|
||||||
|
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
await db.insert(users).values([
|
||||||
|
{ oidcSub: "admin", name: "Alma", role: "admin" },
|
||||||
|
{ oidcSub: "operator", name: "Olle", role: "operator" },
|
||||||
|
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
||||||
|
]);
|
||||||
|
const cred = (await db.insert(integrationCredentials).values({ name: "authentik:Front door", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok", writeToken: "write-tok" })) }).returning({ id: integrationCredentials.id }))[0];
|
||||||
|
const credRead = (await db.insert(integrationCredentials).values({ name: "authentik:Watched", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok" })) }).returning({ id: integrationCredentials.id }))[0];
|
||||||
|
const config = JSON.stringify({ url: fakeUrl });
|
||||||
|
id = (await db.insert(integrations).values({ type: "authentik", name: "Front door", baseUrl: fakeUrl, config, credentialId: cred.id }).returning({ id: integrations.id }))[0].id;
|
||||||
|
readOnly = (await db.insert(integrations).values({ type: "authentik", name: "Watched", baseUrl: fakeUrl, config, credentialId: credRead.id }).returning({ id: integrations.id }))[0].id;
|
||||||
|
const a = express();
|
||||||
|
a.use(express.json());
|
||||||
|
a.use((req, _res, next) => {
|
||||||
|
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
a.use("/api/authentik", authentikRouter);
|
||||||
|
app = await new Promise<Server>((resolve) => {
|
||||||
|
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||||
|
});
|
||||||
|
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/authentik`;
|
||||||
|
});
|
||||||
|
after(() => {
|
||||||
|
app.close();
|
||||||
|
try {
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// Windows keeps the database file locked until the process exits.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("only an administrator sees the users or changes them; nothing reaches Authentik for anyone else", async () => {
|
||||||
|
reset();
|
||||||
|
for (const sub of ["viewer", "operator"]) {
|
||||||
|
assert.equal((await list(sub)).status, 403, sub);
|
||||||
|
assert.equal((await active(3, false, sub)).status, 403, sub);
|
||||||
|
assert.equal((await del(3, "carol", sub)).status, 403, sub);
|
||||||
|
}
|
||||||
|
assert.deepEqual(seen, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the list: the people, whether each is on, which one the token is, and what was searched for", async () => {
|
||||||
|
reset();
|
||||||
|
const res = await list();
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
const body = (await res.json()) as { users: { pk: number; username: string; active: boolean; admin: boolean; lastLogin: string | null }[]; more: boolean; self: number };
|
||||||
|
assert.deepEqual(body.users.map((u) => [u.pk, u.username, u.active, u.admin]), [[1, "akadmin", true, true], [2, "bob", true, true], [3, "carol", true, false], [4, "dave", false, false]]);
|
||||||
|
assert.deepEqual([body.self, body.more], [1, false]);
|
||||||
|
const found = (await (await list("admin", "?search=carol")).json()) as { users: { username: string }[] };
|
||||||
|
assert.deepEqual(found.users.map((u) => u.username), ["carol"]);
|
||||||
|
assert.equal(/write-tok|read-tok/.test(JSON.stringify(body)), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("switching a user off and on: Authentik is asked for exactly that, and the audit log says who did it to whom", async () => {
|
||||||
|
reset();
|
||||||
|
const off = await active(3, false);
|
||||||
|
assert.equal(off.status, 200);
|
||||||
|
assert.equal(((await off.json()) as { user: { active: boolean } }).user.active, false);
|
||||||
|
assert.deepEqual(writes().map((s) => [s.method, s.path, s.body]), [["PATCH", "/api/v3/core/users/3/", JSON.stringify({ is_active: false })]]);
|
||||||
|
assert.equal(table.find((u) => u.pk === 3)!.is_active, false);
|
||||||
|
const on = await active(3, true);
|
||||||
|
assert.equal(on.status, 200);
|
||||||
|
assert.equal(table.find((u) => u.pk === 3)!.is_active, true);
|
||||||
|
const [d] = await audit("disable_authentik_user");
|
||||||
|
const [e] = await audit("enable_authentik_user");
|
||||||
|
for (const entry of [d, e]) {
|
||||||
|
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "3"]);
|
||||||
|
assert.match(entry.detail ?? "", /carol/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a service account, the account the token belongs to, and the last active administrator are refused — and not touched", 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 active(5, false), /service account/);
|
||||||
|
await refused(await del(5, "ak-outpost-front"), /service account/);
|
||||||
|
await refused(await active(1, false), /token/);
|
||||||
|
await refused(await del(1, "akadmin"), /token/);
|
||||||
|
assert.deepEqual(writes(), []);
|
||||||
|
// The token is somebody else's now, and bob is the only other administrator: with bob off, akadmin is the last one holding the door.
|
||||||
|
meId = 3;
|
||||||
|
assert.equal((await active(2, false)).status, 200, "there is still akadmin");
|
||||||
|
await refused(await active(1, false), /only active administrator/);
|
||||||
|
await refused(await del(1, "akadmin"), /only active administrator/);
|
||||||
|
assert.deepEqual(writes().map((s) => s.path), ["/api/v3/core/users/2/"]);
|
||||||
|
assert.equal((await active(5, true)).status, 409, "not even to switch one on");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("deleting: the user name has to match the user now; then they are gone, and it is written down", async () => {
|
||||||
|
reset();
|
||||||
|
assert.equal((await del(4, undefined)).status, 400);
|
||||||
|
assert.equal((await del(4, "")).status, 400);
|
||||||
|
const wrong = await del(4, "carol");
|
||||||
|
assert.equal(wrong.status, 400);
|
||||||
|
assert.equal(((await wrong.json()) as { error: string }).error, "username_mismatch");
|
||||||
|
assert.deepEqual(writes(), []);
|
||||||
|
assert.equal(table.some((u) => u.pk === 4), true);
|
||||||
|
assert.equal((await del(4, "dave")).status, 204);
|
||||||
|
assert.equal(table.some((u) => u.pk === 4), false);
|
||||||
|
assert.deepEqual(writes().map((s) => [s.method, s.path]), [["DELETE", "/api/v3/core/users/4/"]]);
|
||||||
|
const [entry] = await audit("delete_authentik_user");
|
||||||
|
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "4"]);
|
||||||
|
assert.match(entry.detail ?? "", /dave/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a user that is gone, an id that is no id, and a refusal from Authentik itself are told as such", async () => {
|
||||||
|
reset();
|
||||||
|
assert.equal((await active(99, false)).status, 404);
|
||||||
|
assert.equal((await del(99, "x")).status, 404);
|
||||||
|
assert.equal((await active(Number.NaN, false)).status, 400);
|
||||||
|
assert.equal((await fetch(`${base}/${id}/users/1e3/active`, { method: "POST", headers: as("admin"), body: JSON.stringify({ active: false }) })).status, 400);
|
||||||
|
assert.equal((await fetch(`${base}/${id}/users/3/active`, { method: "POST", headers: as("admin"), body: JSON.stringify({ active: "yes" }) })).status, 400);
|
||||||
|
const before = (await audit("disable_authentik_user")).length;
|
||||||
|
patchStatus = 403;
|
||||||
|
const res = await active(3, false);
|
||||||
|
assert.equal(res.status, 502);
|
||||||
|
assert.match(((await res.json()) as { message: string }).message, /did not accept the token/);
|
||||||
|
assert.equal((await audit("disable_authentik_user")).length, before, "nothing was done, so nothing more is written down");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an Authentik with no token for managing users is not asked anything", async () => {
|
||||||
|
reset();
|
||||||
|
const res = await fetch(`${base}/${readOnly}/users`, { headers: as("admin") });
|
||||||
|
assert.equal(res.status, 400);
|
||||||
|
assert.equal(((await res.json()) as { error: string }).error, "no_write_token");
|
||||||
|
assert.equal((await active(3, false, "admin", readOnly)).status, 400);
|
||||||
|
assert.deepEqual(seen, []);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1771,6 +1771,18 @@ export interface AuthentikNewUser {
|
|||||||
groups: string[];
|
groups: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A person in Authentik, as the list that looks after them shows them. */
|
||||||
|
export interface AuthentikPerson {
|
||||||
|
pk: number;
|
||||||
|
username: string;
|
||||||
|
name: string;
|
||||||
|
email: string | null;
|
||||||
|
active: boolean;
|
||||||
|
/** May do everything in Authentik. */
|
||||||
|
admin: boolean;
|
||||||
|
lastLogin: 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). */
|
||||||
export interface AuthentikUserMade {
|
export interface AuthentikUserMade {
|
||||||
user: { pk: number; username: string; name: string };
|
user: { pk: number; username: string; name: string };
|
||||||
@@ -3412,6 +3424,9 @@ export const api = {
|
|||||||
list: () => request<{ authentiks: AuthentikInfo[] }>("/api/authentik"),
|
list: () => request<{ authentiks: AuthentikInfo[] }>("/api/authentik"),
|
||||||
groups: (id: number) => request<{ groups: AuthentikGroup[] }>(`/api/authentik/${id}/groups`),
|
groups: (id: number) => request<{ groups: AuthentikGroup[] }>(`/api/authentik/${id}/groups`),
|
||||||
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())}` : ""}`),
|
||||||
|
setUserActive: (id: number, pk: number, active: boolean) => request<{ user: AuthentikPerson }>(`/api/authentik/${id}/users/${pk}/active`, { method: "POST", body: JSON.stringify({ active }) }),
|
||||||
|
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" }),
|
||||||
},
|
},
|
||||||
jellyfin: {
|
jellyfin: {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export default function AuthentikNewUser({ a, onChanged }: { a: AuthentikInfo; o
|
|||||||
if (!a.canCreateUsers) {
|
if (!a.canCreateUsers) {
|
||||||
return (
|
return (
|
||||||
<div className="text-secondary small mt-3">
|
<div className="text-secondary small mt-3">
|
||||||
To make users from here, give this Authentik a token that may add users: <Link to="/integrations">Integrations</Link> → edit → <em>Token for making users</em>.
|
To make and manage users from here, give this Authentik a token that may add, change and delete them: <Link to="/integrations">Integrations</Link> → edit → <em>Token for making and managing users</em>.
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -68,7 +68,7 @@ export default function AuthentikNewUser({ a, onChanged }: { a: AuthentikInfo; o
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function stopAllowing() {
|
async function stopAllowing() {
|
||||||
if (!(await confirmDialog({ title: "Stop making users", message: `Remove the token for making users from "${a.name}"? Reading it carries on. You can add one again under Integrations.`, confirmLabel: "Remove", danger: true }))) return;
|
if (!(await confirmDialog({ title: "Stop managing users", message: `Remove the token for making and managing users from "${a.name}"? Reading it carries on. You can add one again under Integrations.`, confirmLabel: "Remove", danger: true }))) return;
|
||||||
try {
|
try {
|
||||||
await api.authentik.removeWriteToken(a.id);
|
await api.authentik.removeWriteToken(a.id);
|
||||||
close();
|
close();
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { useState, type FormEvent } from "react";
|
||||||
|
import { api, type AuthentikInfo, type AuthentikPerson } from "../api/client";
|
||||||
|
import TimeAgo from "./TimeAgo";
|
||||||
|
import { ErrorNotice } from "./Notice";
|
||||||
|
import { confirmDialog, promptDialog } from "../utils/dialogs";
|
||||||
|
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 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 }) {
|
||||||
|
const [people, setPeople] = useState<AuthentikPerson[] | null>(null);
|
||||||
|
const [more, setMore] = useState(false);
|
||||||
|
const [self, setSelf] = useState<number | null>(null);
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [busy, setBusy] = useState<number | "list" | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
if (!a.canCreateUsers) return null;
|
||||||
|
|
||||||
|
async function load(q = search) {
|
||||||
|
setBusy("list");
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const r = await api.authentik.users(a.id, q);
|
||||||
|
setPeople(r.users);
|
||||||
|
setMore(r.more);
|
||||||
|
setSelf(r.self);
|
||||||
|
} catch (err) {
|
||||||
|
setError(readableError(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function find(e: FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
void load();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function switchTo(p: AuthentikPerson, on: boolean) {
|
||||||
|
if (!on) {
|
||||||
|
const ok = await confirmDialog({
|
||||||
|
title: "Switch off user",
|
||||||
|
message: `Switch off "${p.username}" in ${a.name}? They can no longer sign in to anything behind Authentik. Nothing of theirs is lost, and switching on again brings it all back. A session they already have in this app is not ended by this — end it under Users → Signed in now.`,
|
||||||
|
confirmLabel: "Switch off",
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
|
setBusy(p.pk);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await api.authentik.setUserActive(a.id, p.pk, on);
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
setError(readableError(err));
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(p: AuthentikPerson) {
|
||||||
|
const typed = await promptDialog({
|
||||||
|
title: "Delete user",
|
||||||
|
message: `This deletes "${p.username}" in ${a.name} for good, with their account there. It cannot be undone — switching them off is the way back. Type the user name to confirm.`,
|
||||||
|
label: "User name",
|
||||||
|
confirmLabel: "Delete",
|
||||||
|
required: true,
|
||||||
|
});
|
||||||
|
if (typed === null) return;
|
||||||
|
if (typed.trim() !== p.username) {
|
||||||
|
setError("That is not the user name, so nothing was deleted.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(p.pk);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await api.authentik.deleteUser(a.id, p.pk, p.username);
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
setError(readableError(err));
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-3">
|
||||||
|
<h4>Users</h4>
|
||||||
|
<ErrorNotice error={error} />
|
||||||
|
{people === null ? (
|
||||||
|
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => void load()} disabled={busy !== null}>
|
||||||
|
{busy === "list" ? "Reading…" : "Show users"}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<form onSubmit={find} className="input-group input-group-sm mb-2" style={{ maxWidth: 360 }}>
|
||||||
|
<input className="form-control" placeholder="Search by name or email" aria-label="Search users" maxLength={100} value={search} onChange={(e) => setSearch(e.target.value)} />
|
||||||
|
<button type="submit" className="btn btn-outline-secondary" disabled={busy !== null}>
|
||||||
|
Search
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{people.length === 0 ? (
|
||||||
|
<div className="text-secondary mb-2">No users{search.trim() ? " match that" : ""}.</div>
|
||||||
|
) : (
|
||||||
|
<div className="table-responsive">
|
||||||
|
<table className="table table-vcenter table-sm">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>User</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Last sign-in</th>
|
||||||
|
<th className="text-end"> </th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{people.map((p) => (
|
||||||
|
<tr key={p.pk} className={p.active ? "" : "text-secondary"}>
|
||||||
|
<td>
|
||||||
|
{p.username}
|
||||||
|
{p.name !== p.username && <span className="text-secondary"> — {p.name}</span>}
|
||||||
|
{p.email && <div className="small text-secondary">{p.email}</div>}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{p.active ? <span className="badge bg-green-lt text-green">On</span> : <span className="badge bg-secondary-lt text-secondary">Off</span>}
|
||||||
|
{p.admin && <span className="badge bg-yellow-lt text-yellow ms-1">administrator</span>}
|
||||||
|
</td>
|
||||||
|
<td className="text-secondary">{p.lastLogin ? <TimeAgo value={p.lastLogin} /> : "never"}</td>
|
||||||
|
<td className="text-end text-nowrap">
|
||||||
|
{p.pk === self ? (
|
||||||
|
<span className="small text-secondary" title="The account the token for managing users belongs to; it is looked after in Authentik.">
|
||||||
|
this token’s account
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<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"}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn btn-sm btn-outline-danger" disabled={busy !== null} onClick={() => void remove(p)}>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{more && <div className="text-secondary small mb-2">Only the first 200 are shown — search to find the others.</div>}
|
||||||
|
<button type="button" className="btn btn-sm btn-link text-secondary px-0" onClick={() => setPeople(null)}>
|
||||||
|
Hide users
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { api, type AuthentikInfo, type CurrentUser } from "../api/client";
|
import { api, type AuthentikInfo, type CurrentUser } from "../api/client";
|
||||||
import AuthentikNewUser from "../components/AuthentikNewUser";
|
import AuthentikNewUser from "../components/AuthentikNewUser";
|
||||||
|
import AuthentikUserList from "../components/AuthentikUserList";
|
||||||
import EmptyState from "../components/EmptyState";
|
import EmptyState from "../components/EmptyState";
|
||||||
import TimeAgo from "../components/TimeAgo";
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { BlockSkeleton } from "../components/Skeleton";
|
import { BlockSkeleton } from "../components/Skeleton";
|
||||||
@@ -128,6 +129,7 @@ function Card({ a, isAdmin, onChanged }: { a: AuthentikInfo; isAdmin: boolean; o
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{isAdmin && a.enabled && <AuthentikNewUser a={a} onChanged={onChanged} />}
|
{isAdmin && a.enabled && <AuthentikNewUser a={a} onChanged={onChanged} />}
|
||||||
|
{isAdmin && a.enabled && <AuthentikUserList a={a} />}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -158,7 +160,7 @@ export default function Authentik({ user }: { user: CurrentUser }) {
|
|||||||
<h2 className="page-title">Authentik</h2>
|
<h2 className="page-title">Authentik</h2>
|
||||||
<p className="text-secondary">
|
<p className="text-secondary">
|
||||||
The sign-in in front of everything else. It is read every few minutes with an API token (see <Link to="/integrations">Integrations</Link>). An <strong>outpost that goes quiet</strong> (the apps it guards stop letting anyone in), a <strong>certificate</strong> or an{" "}
|
The sign-in in front of everything else. It is read every few minutes with an API token (see <Link to="/integrations">Integrations</Link>). An <strong>outpost that goes quiet</strong> (the apps it guards stop letting anyone in), a <strong>certificate</strong> or an{" "}
|
||||||
<strong>API token</strong> that is about to run out, <strong>no worker</strong> and a burst of <strong>failed sign-ins</strong> are alerts — see <Link to="/alerts">Alerts</Link>.{user.role === "admin" && " An administrator can also make a user here, with a one-time link for them to choose a password."}
|
<strong>API token</strong> that is about to run out, <strong>no worker</strong> and a burst of <strong>failed sign-ins</strong> are alerts — see <Link to="/alerts">Alerts</Link>.{user.role === "admin" && " An administrator can also make a user here, with a one-time link for them to choose a password, and switch users off or delete them."}
|
||||||
</p>
|
</p>
|
||||||
<ErrorNotice error={error} />
|
<ErrorNotice error={error} />
|
||||||
{!data && !error && <BlockSkeleton lines={4} />}
|
{!data && !error && <BlockSkeleton lines={4} />}
|
||||||
|
|||||||
Reference in new issue
Block a user