This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/web/src/admin/users/UserListPage.ts
Ken Sternberg a2dce3fb63
web: Replace calls to rootInterface()?.tenant? with a contextual this.tenant object (#7778)
* This commit abstracts access to the object `rootInterface()?.config?` into a single accessor,
`authentikConfig`, that can be mixed into any AKElement object that requires access to it.

Since access to `rootInterface()?.config?` is _universally_ used for a single (and repetitive)
boolean check, a separate accessor has been provided that converts all calls of the form:

``` javascript
rootInterface()?.config?.capabilities.includes(CapabilitiesEnum.CanImpersonate)
```

into:

``` javascript
this.can(CapabilitiesEnum.CanImpersonate)
```

It does this via a Mixin, `WithCapabilitiesConfig`, which understands that these calls only make
sense in the context of a running, fully configured authentik instance, and that their purpose is to
inform authentik components of a user’s capabilities. The latter is why I don’t feel uncomfortable
turning a function call into a method; we should make it explicit that this is a relationship
between components.

The mixin has a single single field, `[WCC.capabilitiesConfig]`, where its association with the
upper-level configuration is made. If that syntax looks peculiar to you, good! I’ve used an explict
unique symbol as the field name; it is inaccessable an innumerable in the object list. The debugger
shows it only as:

    Symbol(): {
        cacheTimeout: 300
        cacheTimeoutFlows: 300
        cacheTimeoutPolicies: 300
        cacheTimeoutReputation: 300
        capabilities: (5) ['can_save_media', 'can_geo_ip', 'can_impersonate', 'can_debug', 'is_enterprise']
    }

Since you can’t reference it by identity, you can’t write to it. Until every browser supports actual
private fields, this is the best we can do; it does guarantee that field name collisions are
impossible, which is a win.

The mixin takes a second optional boolean; setting this to true will cause any web component using
the mixin to automatically schedule a re-render if the capabilities list changes.

The mixin is also generic; despite the "...into a Lit-Context" in the title, the internals of the
Mixin can be replaced with anything so long as the signature of `.can()` is preserved.

Because this work builds off the work I did to give the Sidebar access to the configuration without
ad-hoc retrieval or prop-drilling, it wasn’t necessary to create a new context for it. That will be
necessary for the following:

TODO:

``` javascript
rootInterface()?.uiConfig;
rootInterface()?.tenant;
me();
```

* This commit abstracts access to the object `rootInterface()?.tenant?` into a single accessor,
`tenant`, that can be mixed into any AKElement object that requires access to it.

Like `WithCapabilitiesConfig` and `WithAuthentikConfig`, this one is named `WithTenantConfig`.

TODO:

``` javascript
rootInterface()?.uiConfig;
me();
```

* web: Added a README with a description of the applications' "mental model," essentially an architectural description.

* web: prettier did a thing

* web: prettier had opinions about the README

* web: Jens requested that subscription be  by default, and it's the right call.

* web: Jens requested that the default subscription state for contexts be , and it's the right call.

* web: prettier having opinions after merging with dependent branch

* web: prettier still having opinions.
2024-01-08 13:03:00 -08:00

419 lines
19 KiB
TypeScript

import { AdminInterface } from "@goauthentik/admin/AdminInterface";
import "@goauthentik/admin/users/ServiceAccountForm";
import "@goauthentik/admin/users/UserActiveForm";
import "@goauthentik/admin/users/UserForm";
import "@goauthentik/admin/users/UserPasswordForm";
import "@goauthentik/admin/users/UserResetEmailForm";
import { me } from "@goauthentik/app/common/users";
import { DEFAULT_CONFIG } from "@goauthentik/common/api/config";
import { userTypeToLabel } from "@goauthentik/common/labels";
import { MessageLevel } from "@goauthentik/common/messages";
import { DefaultUIConfig, uiConfig } from "@goauthentik/common/ui/config";
import { first } from "@goauthentik/common/utils";
import "@goauthentik/components/ak-status-label";
import { rootInterface } from "@goauthentik/elements/Base";
import {
CapabilitiesEnum,
WithCapabilitiesConfig,
} from "@goauthentik/elements/Interface/capabilitiesProvider";
import { WithTenantConfig } from "@goauthentik/elements/Interface/tenantProvider";
import { PFSize } from "@goauthentik/elements/Spinner";
import "@goauthentik/elements/TreeView";
import "@goauthentik/elements/buttons/ActionButton";
import "@goauthentik/elements/forms/DeleteBulkForm";
import "@goauthentik/elements/forms/ModalForm";
import { showMessage } from "@goauthentik/elements/messages/MessageContainer";
import { getURLParam, updateURLParams } from "@goauthentik/elements/router/RouteMatch";
import { PaginatedResponse } from "@goauthentik/elements/table/Table";
import { TableColumn } from "@goauthentik/elements/table/Table";
import { TablePage } from "@goauthentik/elements/table/TablePage";
import { writeToClipboard } from "@goauthentik/elements/utils/writeToClipboard";
import "@patternfly/elements/pf-tooltip/pf-tooltip.js";
import { msg, str } from "@lit/localize";
import { CSSResult, TemplateResult, css, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import PFAlert from "@patternfly/patternfly/components/Alert/alert.css";
import PFCard from "@patternfly/patternfly/components/Card/card.css";
import PFDescriptionList from "@patternfly/patternfly/components/DescriptionList/description-list.css";
import { CoreApi, ResponseError, SessionUser, User, UserPath } from "@goauthentik/api";
export const requestRecoveryLink = (user: User) =>
new CoreApi(DEFAULT_CONFIG)
.coreUsersRecoveryRetrieve({
id: user.pk,
})
.then((rec) =>
writeToClipboard(rec.link).then((wroteToClipboard) =>
showMessage({
level: MessageLevel.success,
message: rec.link,
description: wroteToClipboard
? msg("A copy of this recovery link has been placed in your clipboard")
: "",
}),
),
)
.catch((ex: ResponseError) =>
ex.response.json().then(() =>
showMessage({
level: MessageLevel.error,
message: msg(
"The current tenant must have a recovery flow configured to use a recovery link",
),
}),
),
);
export const renderRecoveryEmailRequest = (user: User) =>
html`<ak-forms-modal .closeAfterSuccessfulSubmit=${false} id="ak-email-recovery-request">
<span slot="submit"> ${msg("Send link")} </span>
<span slot="header"> ${msg("Send recovery link to user")} </span>
<ak-user-reset-email-form slot="form" .user=${user}> </ak-user-reset-email-form>
<button slot="trigger" class="pf-c-button pf-m-secondary">
${msg("Email recovery link")}
</button>
</ak-forms-modal>`;
const recoveryButtonStyles = css`
#recovery-request-buttons {
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 0.375rem;
}
#recovery-request-buttons > *,
#update-password-request .pf-c-button {
margin: 0;
}
`;
@customElement("ak-user-list")
export class UserListPage extends WithTenantConfig(WithCapabilitiesConfig(TablePage<User>)) {
expandable = true;
checkbox = true;
searchEnabled(): boolean {
return true;
}
pageTitle(): string {
return msg("Users");
}
pageDescription(): string {
return "";
}
pageIcon(): string {
return "pf-icon pf-icon-user";
}
@property()
order = "last_login";
@property()
activePath;
@state()
hideDeactivated = getURLParam<boolean>("hideDeactivated", false);
@state()
userPaths?: UserPath;
@state()
me?: SessionUser;
static get styles(): CSSResult[] {
return [...super.styles, PFDescriptionList, PFCard, PFAlert, recoveryButtonStyles];
}
constructor() {
super();
this.activePath = getURLParam<string>("path", "/");
uiConfig().then((c) => {
if (c.defaults.userPath !== new DefaultUIConfig().defaults.userPath) {
this.activePath = c.defaults.userPath;
}
});
}
async apiEndpoint(page: number): Promise<PaginatedResponse<User>> {
const users = await new CoreApi(DEFAULT_CONFIG).coreUsersList({
ordering: this.order,
page: page,
pageSize: (await uiConfig()).pagination.perPage,
search: this.search || "",
pathStartswith: getURLParam("path", ""),
isActive: this.hideDeactivated ? true : undefined,
});
this.userPaths = await new CoreApi(DEFAULT_CONFIG).coreUsersPathsRetrieve({
search: this.search,
});
this.me = await me();
return users;
}
columns(): TableColumn[] {
return [
new TableColumn(msg("Name"), "username"),
new TableColumn(msg("Active"), "is_active"),
new TableColumn(msg("Last login"), "last_login"),
new TableColumn(msg("Actions")),
];
}
renderToolbarSelected(): TemplateResult {
const disabled = this.selectedElements.length < 1;
const currentUser = rootInterface<AdminInterface>()?.user;
const shouldShowWarning = this.selectedElements.find((el) => {
return el.pk === currentUser?.user.pk || el.pk == currentUser?.original?.pk;
});
return html`<ak-forms-delete-bulk
objectLabel=${msg("User(s)")}
.objects=${this.selectedElements}
.metadata=${(item: User) => {
return [
{ key: msg("Username"), value: item.username },
{ key: msg("ID"), value: item.pk.toString() },
{ key: msg("UID"), value: item.uid },
];
}}
.usedBy=${(item: User) => {
return new CoreApi(DEFAULT_CONFIG).coreUsersUsedByList({
id: item.pk,
});
}}
.delete=${(item: User) => {
return new CoreApi(DEFAULT_CONFIG).coreUsersDestroy({
id: item.pk,
});
}}
>
${shouldShowWarning
? html`<div slot="notice" class="pf-c-form__alert">
<div class="pf-c-alert pf-m-inline pf-m-warning">
<div class="pf-c-alert__icon">
<i class="fas fa-exclamation-circle"></i>
</div>
<h4 class="pf-c-alert__title">
${msg(
str`Warning: You're about to delete the user you're logged in as (${shouldShowWarning.username}). Proceed at your own risk.`,
)}
</h4>
</div>
</div>`
: html``}
<button ?disabled=${disabled} slot="trigger" class="pf-c-button pf-m-danger">
${msg("Delete")}
</button>
</ak-forms-delete-bulk>`;
}
renderToolbarAfter(): TemplateResult {
return html`&nbsp;
<div class="pf-c-toolbar__group pf-m-filter-group">
<div class="pf-c-toolbar__item pf-m-search-filter">
<div class="pf-c-input-group">
<label class="pf-c-switch">
<input
class="pf-c-switch__input"
type="checkbox"
?checked=${this.hideDeactivated}
@change=${() => {
this.hideDeactivated = !this.hideDeactivated;
this.page = 1;
this.fetch();
updateURLParams({
hideDeactivated: this.hideDeactivated,
});
}}
/>
<span class="pf-c-switch__toggle">
<span class="pf-c-switch__toggle-icon">
<i class="fas fa-check" aria-hidden="true"></i>
</span>
</span>
<span class="pf-c-switch__label">${msg("Hide deactivated user")}</span>
</label>
</div>
</div>
</div>`;
}
row(item: User): TemplateResult[] {
const canImpersonate =
this.can(CapabilitiesEnum.CanImpersonate) && item.pk !== this.me?.user.pk;
return [
html`<a href="#/identity/users/${item.pk}">
<div>${item.username}</div>
<small>${item.name === "" ? msg("<No name set>") : item.name}</small> </a
>&nbsp;<small>${userTypeToLabel(item.type)}</small>`,
html`<ak-status-label ?good=${item.isActive}></ak-status-label>`,
html`${first(item.lastLogin?.toLocaleString(), msg("-"))}`,
html`<ak-forms-modal>
<span slot="submit"> ${msg("Update")} </span>
<span slot="header"> ${msg("Update User")} </span>
<ak-user-form slot="form" .instancePk=${item.pk}> </ak-user-form>
<button slot="trigger" class="pf-c-button pf-m-plain">
<pf-tooltip position="top" content=${msg("Edit")}>
<i class="fas fa-edit"></i>
</pf-tooltip>
</button>
</ak-forms-modal>
${canImpersonate
? html`
<ak-action-button
class="pf-m-tertiary"
.apiRequest=${() => {
return new CoreApi(DEFAULT_CONFIG)
.coreUsersImpersonateCreate({
id: item.pk,
})
.then(() => {
window.location.href = "/";
});
}}
>
${msg("Impersonate")}
</ak-action-button>
`
: html``}`,
];
}
renderExpanded(item: User): TemplateResult {
return html`<td role="cell" colspan="3">
<div class="pf-c-table__expandable-row-content">
<dl class="pf-c-description-list pf-m-horizontal">
<div class="pf-c-description-list__group">
<dt class="pf-c-description-list__term">
<span class="pf-c-description-list__text"
>${msg("User status")}</span
>
</dt>
<dd class="pf-c-description-list__description">
<div class="pf-c-description-list__text">
${item.isActive ? msg("Active") : msg("Inactive")}
</div>
<div class="pf-c-description-list__text">
${item.isSuperuser ? msg("Superuser") : msg("Regular user")}
</div>
</dd>
</div>
<div class="pf-c-description-list__group">
<dt class="pf-c-description-list__term">
<span class="pf-c-description-list__text"
>${msg("Change status")}</span
>
</dt>
<dd class="pf-c-description-list__description">
<div class="pf-c-description-list__text">
<ak-user-active-form
.obj=${item}
objectLabel=${msg("User")}
.delete=${() => {
return new CoreApi(
DEFAULT_CONFIG,
).coreUsersPartialUpdate({
id: item.pk,
patchedUserRequest: {
isActive: !item.isActive,
},
});
}}
>
<button slot="trigger" class="pf-c-button pf-m-warning">
${item.isActive ? msg("Deactivate") : msg("Activate")}
</button>
</ak-user-active-form>
</div>
</dd>
</div>
<div class="pf-c-description-list__group">
<dt class="pf-c-description-list__term">
<span class="pf-c-description-list__text">${msg("Recovery")}</span>
</dt>
<dd class="pf-c-description-list__description">
<div
class="pf-c-description-list__text"
id="recovery-request-buttons"
>
<ak-forms-modal
size=${PFSize.Medium}
id="update-password-request"
>
<span slot="submit">${msg("Update password")}</span>
<span slot="header">${msg("Update password")}</span>
<ak-user-password-form
slot="form"
.instancePk=${item.pk}
></ak-user-password-form>
<button slot="trigger" class="pf-c-button pf-m-secondary">
${msg("Set password")}
</button>
</ak-forms-modal>
${this.tenant.flowRecovery
? html`
<ak-action-button
class="pf-m-secondary"
.apiRequest=${() => requestRecoveryLink(item)}
>
${msg("Create recovery link")}
</ak-action-button>
${item.email
? renderRecoveryEmailRequest(item)
: html`<span
>${msg(
"Recovery link cannot be emailed, user has no email address saved.",
)}</span
>`}
`
: html` <p>
${msg(
"To let a user directly reset a their password, configure a recovery flow on the currently active tenant.",
)}
</p>`}
</div>
</dd>
</div>
</dl>
</div>
</td>
<td></td>
<td></td>`;
}
renderObjectCreate(): TemplateResult {
return html`
<ak-forms-modal>
<span slot="submit"> ${msg("Create")} </span>
<span slot="header"> ${msg("Create User")} </span>
<ak-user-form slot="form"> </ak-user-form>
<button slot="trigger" class="pf-c-button pf-m-primary">${msg("Create")}</button>
</ak-forms-modal>
<ak-forms-modal .closeAfterSuccessfulSubmit=${false} .cancelText=${msg("Close")}>
<span slot="submit"> ${msg("Create")} </span>
<span slot="header"> ${msg("Create Service account")} </span>
<ak-user-service-account-form slot="form"> </ak-user-service-account-form>
<button slot="trigger" class="pf-c-button pf-m-secondary">
${msg("Create Service account")}
</button>
</ak-forms-modal>
`;
}
renderSidebarBefore(): TemplateResult {
return html`<div class="pf-c-sidebar__panel pf-m-width-25">
<div class="pf-c-card">
<div class="pf-c-card__title">${msg("User folders")}</div>
<div class="pf-c-card__body">
<ak-treeview
.items=${this.userPaths?.paths || []}
activePath=${this.activePath}
></ak-treeview>
</div>
</div>
</div>`;
}
}