stages/authenticator_*: migrate remaining stages to webcomponents

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-03-24 19:48:48 +01:00
parent 1ef5a8e6c5
commit a085632b8e
20 changed files with 280 additions and 259 deletions

View File

@ -1,4 +1,6 @@
"""Authenticator Static stage"""
from importlib import import_module
from django.apps import AppConfig
@ -8,4 +10,6 @@ class AuthentikStageAuthenticatorStaticConfig(AppConfig):
name = "authentik.stages.authenticator_static"
label = "authentik_stages_authenticator_static"
verbose_name = "authentik Stages.Authenticator.Static"
mountpoint = "-/user/authenticator/static/"
def ready(self):
import_module("authentik.stages.authenticator_static.signals")

View File

@ -3,12 +3,11 @@ from typing import Optional, Type
from django.db import models
from django.forms import ModelForm
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views import View
from rest_framework.serializers import BaseSerializer
from authentik.flows.challenge import Challenge, ChallengeTypes
from authentik.core.types import UserSettingSerializer
from authentik.flows.models import ConfigurableStage, Stage
@ -42,15 +41,11 @@ class AuthenticatorStaticStage(ConfigurableStage, Stage):
return AuthenticatorStaticStageForm
@property
def ui_user_settings(self) -> Optional[Challenge]:
return Challenge(
def ui_user_settings(self) -> Optional[UserSettingSerializer]:
return UserSettingSerializer(
data={
"type": ChallengeTypes.shell.value,
"title": str(self._meta.verbose_name),
"component": reverse(
"authentik_stages_authenticator_static:user-settings",
kwargs={"stage_uuid": self.stage_uuid},
),
"component": "ak-user-settings-authenticator-static",
}
)

View File

@ -0,0 +1,17 @@
"""totp authenticator signals"""
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django_otp.plugins.otp_static.models import StaticDevice
from authentik.events.models import Event
@receiver(pre_delete, sender=StaticDevice)
# pylint: disable=unused-argument
def pre_delete_event(sender, instance: StaticDevice, **_):
# Create event with email notification
event = Event.new(
"static_authenticator_disable", message="User disabled Static OTP Tokens."
)
event.set_user(instance.user)
event.save()

View File

@ -1,31 +0,0 @@
{% load i18n %}
<div class="pf-c-card">
<div class="pf-c-card__title">
{% trans "Static One-Time Passwords" %}
</div>
<div class="pf-c-card__body">
<p>
{% blocktrans with state=state|yesno:"Enabled,Disabled" %}
Status: {{ state }}
{% endblocktrans %}
{% if state %}
<i class="pf-icon pf-icon-ok"></i>
{% else %}
<i class="pf-icon pf-icon-error-circle-o"></i>
{% endif %}
</p>
<ul class="ak-otp-tokens">
{% for token in tokens %}
<li>{{ token.token }}</li>
{% endfor %}
</ul>
{% if not state %}
{% if stage.configure_flow %}
<a href="{% url 'authentik_flows:configure' stage_uuid=stage.stage_uuid %}?next=/%23user" class="ak-root-link pf-c-button pf-m-primary">{% trans "Enable Static Tokens" %}</a>
{% endif %}
{% else %}
<a href="{% url 'authentik_stages_authenticator_static:disable' stage_uuid=stage.stage_uuid %}" class="ak-root-pf-c-button pf-m-danger">{% trans "Disable Static Tokens" %}</a>
{% endif %}
</div>
</div>

View File

@ -1,11 +0,0 @@
"""Static Authenticator urls"""
from django.urls import path
from authentik.stages.authenticator_static.views import DisableView, UserSettingsView
urlpatterns = [
path(
"<uuid:stage_uuid>/settings/", UserSettingsView.as_view(), name="user-settings"
),
path("<uuid:stage_uuid>/disable/", DisableView.as_view(), name="disable"),
]

View File

@ -1,47 +0,0 @@
"""Static Authenticator view Tokens"""
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.views import View
from django.views.generic import TemplateView
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from authentik.events.models import Event
from authentik.stages.authenticator_static.models import AuthenticatorStaticStage
class UserSettingsView(LoginRequiredMixin, TemplateView):
"""View for user settings to control OTP"""
template_name = "stages/authenticator_static/user_settings.html"
def get_context_data(self, **kwargs):
kwargs = super().get_context_data(**kwargs)
stage = get_object_or_404(
AuthenticatorStaticStage, pk=self.kwargs["stage_uuid"]
)
kwargs["stage"] = stage
static_devices = StaticDevice.objects.filter(
user=self.request.user, confirmed=True
)
kwargs["state"] = static_devices.exists()
if static_devices.exists():
kwargs["tokens"] = StaticToken.objects.filter(device=static_devices.first())
return kwargs
class DisableView(LoginRequiredMixin, View):
"""Disable Static Tokens for user"""
# pylint: disable=unused-argument
def get(self, request: HttpRequest, **kwargs) -> HttpResponse:
"""Delete all the devices for user"""
devices = StaticDevice.objects.filter(user=request.user, confirmed=True)
devices.delete()
messages.success(request, "Successfully disabled Static OTP Tokens")
# Create event with email notification
Event.new(
"static_otp_disable", message="User disabled Static OTP Tokens."
).from_http(request)
return redirect("/")

View File

@ -1,4 +1,6 @@
"""OTP Time"""
"""TOTP"""
from importlib import import_module
from django.apps import AppConfig
@ -8,4 +10,6 @@ class AuthentikStageAuthenticatorTOTPConfig(AppConfig):
name = "authentik.stages.authenticator_totp"
label = "authentik_stages_authenticator_totp"
verbose_name = "authentik Stages.Authenticator.TOTP"
mountpoint = "-/user/authenticator/totp/"
def ready(self):
import_module("authentik.stages.authenticator_totp.signals")

View File

@ -3,12 +3,11 @@ from typing import Optional, Type
from django.db import models
from django.forms import ModelForm
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views import View
from rest_framework.serializers import BaseSerializer
from authentik.flows.challenge import Challenge, ChallengeTypes
from authentik.core.types import UserSettingSerializer
from authentik.flows.models import ConfigurableStage, Stage
@ -45,15 +44,11 @@ class AuthenticatorTOTPStage(ConfigurableStage, Stage):
return AuthenticatorTOTPStageForm
@property
def ui_user_settings(self) -> Optional[Challenge]:
return Challenge(
def ui_user_settings(self) -> Optional[UserSettingSerializer]:
return UserSettingSerializer(
data={
"type": ChallengeTypes.shell.value,
"title": str(self._meta.verbose_name),
"component": reverse(
"authentik_stages_authenticator_totp:user-settings",
kwargs={"stage_uuid": self.stage_uuid},
),
"component": "ak-user-settings-authenticator-totp",
}
)

View File

@ -0,0 +1,15 @@
"""totp authenticator signals"""
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django_otp.plugins.otp_totp.models import TOTPDevice
from authentik.events.models import Event
@receiver(pre_delete, sender=TOTPDevice)
# pylint: disable=unused-argument
def pre_delete_event(sender, instance: TOTPDevice, **_):
# Create event with email notification
event = Event.new("totp_disable", message="User disabled Time-based OTP.")
event.set_user(instance.user)
event.save()

View File

@ -1,28 +0,0 @@
{% load i18n %}
<div class="pf-c-card">
<div class="pf-c-card__title">
{% trans "Time-based One-Time Passwords" %}
</div>
<div class="pf-c-card__body">
<p>
{% blocktrans with state=state|yesno:"Enabled,Disabled" %}
Status: {{ state }}
{% endblocktrans %}
{% if state %}
<i class="pf-icon pf-icon-ok"></i>
{% else %}
<i class="pf-icon pf-icon-error-circle-o"></i>
{% endif %}
</p>
<p>
{% if not state %}
{% if stage.configure_flow %}
<a href="{% url 'authentik_flows:configure' stage_uuid=stage.stage_uuid %}?next=/%23user" class="ak-root-link pf-c-button pf-m-primary">{% trans "Enable Time-based OTP" %}</a>
{% endif %}
{% else %}
<a href="{% url 'authentik_stages_authenticator_totp:disable' stage_uuid=stage.stage_uuid %}" class="ak-root-pf-c-button pf-m-danger">{% trans "Disable Time-based OTP" %}</a>
{% endif %}
</p>
</div>
</div>

View File

@ -1,11 +0,0 @@
"""OTP Time urls"""
from django.urls import path
from authentik.stages.authenticator_totp.views import DisableView, UserSettingsView
urlpatterns = [
path(
"<uuid:stage_uuid>/settings/", UserSettingsView.as_view(), name="user-settings"
),
path("<uuid:stage_uuid>/disable/", DisableView.as_view(), name="disable"),
]

View File

@ -1,42 +0,0 @@
"""otp time-based view"""
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.views import View
from django.views.generic import TemplateView
from django_otp.plugins.otp_totp.models import TOTPDevice
from authentik.events.models import Event
from authentik.stages.authenticator_totp.models import AuthenticatorTOTPStage
class UserSettingsView(LoginRequiredMixin, TemplateView):
"""View for user settings to control OTP"""
template_name = "stages/authenticator_totp/user_settings.html"
def get_context_data(self, **kwargs):
kwargs = super().get_context_data(**kwargs)
stage = get_object_or_404(AuthenticatorTOTPStage, pk=self.kwargs["stage_uuid"])
kwargs["stage"] = stage
totp_devices = TOTPDevice.objects.filter(user=self.request.user, confirmed=True)
kwargs["state"] = totp_devices.exists()
return kwargs
class DisableView(LoginRequiredMixin, View):
"""Disable TOTP for user"""
# pylint: disable=unused-argument
def get(self, request: HttpRequest, **kwargs) -> HttpResponse:
"""Delete all the devices for user"""
totp = TOTPDevice.objects.filter(user=request.user, confirmed=True)
totp.delete()
messages.success(request, "Successfully disabled Time-based OTP")
# Create event with email notification
Event.new("totp_disable", message="User disabled Time-based OTP.").from_http(
request
)
return redirect("/")

View File

@ -13,6 +13,21 @@ import "../../../elements/forms/FormElement";
import "../../../elements/EmptyState";
import "../../FormStatic";
export const STATIC_TOKEN_STYLE = css`
/* Static OTP Tokens */
.ak-otp-tokens {
list-style: circle;
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
margin-left: var(--pf-global--spacer--xs);
}
.ak-otp-tokens li {
font-size: var(--pf-global--FontSize--2xl);
font-family: monospace;
}
`;
export interface AuthenticatorStaticChallenge extends WithUserInfoChallenge {
codes: number[];
}
@ -24,20 +39,7 @@ export class AuthenticatorStaticStage extends BaseStage {
challenge?: AuthenticatorStaticChallenge;
static get styles(): CSSResult[] {
return [PFBase, PFLogin, PFForm, PFFormControl, PFTitle, PFButton, AKGlobal].concat(css`
/* Static OTP Tokens */
.ak-otp-tokens {
list-style: circle;
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
margin-left: var(--pf-global--spacer--xs);
}
.ak-otp-tokens li {
font-size: var(--pf-global--FontSize--2xl);
font-family: monospace;
}
`);
return [PFBase, PFLogin, PFForm, PFFormControl, PFTitle, PFButton, AKGlobal, STATIC_TOKEN_STYLE];
}
render(): TemplateResult {

View File

@ -20,8 +20,10 @@ import { ifDefined } from "lit-html/directives/if-defined";
import "../../elements/Tabs";
import "../tokens/UserTokenList";
import "../generic/SiteShell";
import "./settings/AuthenticatorWebAuthnDevices";
import "./settings/Password";
import "./settings/UserSettingsAuthenticatorTOTP";
import "./settings/UserSettingsAuthenticatorStatic";
import "./settings/UserSettingsAuthenticatorWebAuthnDevices";
import "./settings/UserSettingsPassword";
@customElement("ak-user-settings")
export class UserSettingsPage extends LitElement {
@ -38,6 +40,12 @@ export class UserSettingsPage extends LitElement {
case "ak-user-settings-password":
return html`<ak-user-settings-password stageId=${stage.objectUid}>
</ak-user-settings-password>`;
case "ak-user-settings-authenticator-totp":
return html`<ak-user-settings-authenticator-totp stageId=${stage.objectUid}>
</ak-user-settings-authenticator-totp>`;
case "ak-user-settings-authenticator-static":
return html`<ak-user-settings-authenticator-static stageId=${stage.objectUid}>
</ak-user-settings-authenticator-static>`;
default:
return html`<div class="pf-u-display-flex pf-u-justify-content-center">
<div class="pf-u-w-75">

View File

@ -0,0 +1,16 @@
import { CSSResult, LitElement, property } from "lit-element";
import PFBase from "@patternfly/patternfly/patternfly-base.css";
import PFCard from "@patternfly/patternfly/components/Card/card.css";
import PFButton from "@patternfly/patternfly/components/Button/button.css";
import AKGlobal from "../../../authentik.css";
export abstract class BaseUserSettings extends LitElement {
@property()
objectId!: string;
static get styles(): CSSResult[] {
return [PFBase, PFCard, PFButton, AKGlobal];
}
}

View File

@ -1,35 +0,0 @@
import { CSSResult, customElement, html, LitElement, property, TemplateResult } from "lit-element";
import PFBase from "@patternfly/patternfly/patternfly-base.css";
import PFCard from "@patternfly/patternfly/components/Card/card.css";
import PFButton from "@patternfly/patternfly/components/Button/button.css";
import AKGlobal from "../../../authentik.css";
import { gettext } from "django";
import { FlowURLManager } from "../../../api/legacy";
@customElement("ak-user-settings-password")
export class UserSettingsPassword extends LitElement {
@property()
stageId!: string;
static get styles(): CSSResult[] {
return [PFBase, PFCard, PFButton, AKGlobal];
}
render(): TemplateResult {
// For this stage we don't need to check for a configureFlow,
// as the stage won't return any UI Elements if no configureFlow is set.
return html`<div class="pf-c-card">
<div class="pf-c-card__title">
${gettext('Change your password')}
</div>
<div class="pf-c-card__body">
<a href="${FlowURLManager.configure(this.stageId, '?next=/%23user')}"
class="pf-c-button pf-m-primary">
${gettext('Change password')}
</a>
</div>
</div>`;
}
}

View File

@ -0,0 +1,69 @@
import { AuthenticatorsApi, StagesApi } from "authentik-api";
import { gettext } from "django";
import { customElement, html, TemplateResult } from "lit-element";
import { until } from "lit-html/directives/until";
import { DEFAULT_CONFIG } from "../../../api/Config";
import { FlowURLManager } from "../../../api/legacy";
import { BaseUserSettings } from "./BaseUserSettings";
@customElement("ak-user-settings-authenticator-static")
export class UserSettingsAuthenticatorStatic extends BaseUserSettings {
renderEnabled(): TemplateResult {
return html`<div class="pf-c-card__body">
<p>
${gettext("Status: Enabled")}
<i class="pf-icon pf-icon-ok"></i>
</p>
</div>
<div class="pf-c-card__footer">
<button
class="pf-c-button pf-m-danger"
@click=${() => {
return new AuthenticatorsApi(DEFAULT_CONFIG).authenticatorsTotpList({}).then((devices) => {
if (devices.results.length < 1) {
return;
}
// TODO: Handle multiple devices, currently we assume only one TOTP Device
return new AuthenticatorsApi(DEFAULT_CONFIG).authenticatorsTotpDelete({
id: devices.results[0].pk || 0
});
});
}}>
${gettext("Disable Time-based OTP")}
</button>
</div>`;
}
renderDisabled(): TemplateResult {
return html`
<div class="pf-c-card__body">
<p>
${gettext("Status: Disabled")}
<i class="pf-icon pf-icon-error-circle-o"></i>
</p>
</div>
<div class="pf-c-card__footer">
${until(new StagesApi(DEFAULT_CONFIG).stagesAuthenticatorTotpRead({ stageUuid: this.objectId}).then((stage) => {
if (stage.configureFlow) {
return html`<a href="${FlowURLManager.configure(stage.pk || "", "?next=/%23%2Fuser")}"
class="pf-c-button pf-m-primary">${gettext("Enable Time-based OTP")}
</a>`;
}
return html``;
}))}
</div>`;
}
render(): TemplateResult {
return html`<div class="pf-c-card">
<div class="pf-c-card__title">
${gettext("Time-based One-Time Passwords")}
</div>
${until(new AuthenticatorsApi(DEFAULT_CONFIG).authenticatorsTotpList({}).then((devices) => {
return devices.results.length > 0 ? this.renderEnabled() : this.renderDisabled();
}))}
</div>`;
}
}

View File

@ -0,0 +1,84 @@
import { AuthenticatorsApi, StagesApi } from "authentik-api";
import { gettext } from "django";
import { CSSResult, customElement, html, TemplateResult } from "lit-element";
import { until } from "lit-html/directives/until";
import { DEFAULT_CONFIG } from "../../../api/Config";
import { FlowURLManager } from "../../../api/legacy";
import { STATIC_TOKEN_STYLE } from "../../../flows/stages/authenticator_static/AuthenticatorStaticStage";
import { BaseUserSettings } from "./BaseUserSettings";
@customElement("ak-user-settings-authenticator-totp")
export class UserSettingsAuthenticatorTOTP extends BaseUserSettings {
static get styles(): CSSResult[] {
return super.styles.concat(STATIC_TOKEN_STYLE);
}
renderEnabled(): TemplateResult {
return html`<div class="pf-c-card__body">
<p>
${gettext("Status: Enabled")}
<i class="pf-icon pf-icon-ok"></i>
</p>
<ul class="ak-otp-tokens">
${until(new AuthenticatorsApi(DEFAULT_CONFIG).authenticatorsStaticList({}).then((devices) => {
if (devices.results.length < 1) {
return;
}
return devices.results[0].tokenSet?.map((token) => {
return html`<li>${token.token}</li>`;
});
}))}
</ul>
</div>
<div class="pf-c-card__footer">
<button
class="pf-c-button pf-m-danger"
@click=${() => {
return new AuthenticatorsApi(DEFAULT_CONFIG).authenticatorsStaticList({}).then((devices) => {
if (devices.results.length < 1) {
return;
}
// TODO: Handle multiple devices, currently we assume only one TOTP Device
return new AuthenticatorsApi(DEFAULT_CONFIG).authenticatorsStaticDelete({
id: devices.results[0].pk || 0
});
});
}}>
${gettext("Disable Static Tokens")}
</button>
</div>`;
}
renderDisabled(): TemplateResult {
return html`
<div class="pf-c-card__body">
<p>
${gettext("Status: Disabled")}
<i class="pf-icon pf-icon-error-circle-o"></i>
</p>
</div>
<div class="pf-c-card__footer">
${until(new StagesApi(DEFAULT_CONFIG).stagesAuthenticatorStaticRead({ stageUuid: this.objectId}).then((stage) => {
if (stage.configureFlow) {
return html`<a href="${FlowURLManager.configure(stage.pk || "", "?next=/%23%2Fuser")}"
class="pf-c-button pf-m-primary">${gettext("Enable Static Tokens")}
</a>`;
}
return html``;
}))}
</div>`;
}
render(): TemplateResult {
return html`<div class="pf-c-card">
<div class="pf-c-card__title">
${gettext("Static Tokens")}
</div>
${until(new AuthenticatorsApi(DEFAULT_CONFIG).authenticatorsTotpList({}).then((devices) => {
return devices.results.length > 0 ? this.renderEnabled() : this.renderDisabled();
}))}
</div>`;
}
}

View File

@ -1,24 +1,16 @@
import { CSSResult, customElement, html, LitElement, property, TemplateResult } from "lit-element";
import PFBase from "@patternfly/patternfly/patternfly-base.css";
import PFCard from "@patternfly/patternfly/components/Card/card.css";
import PFDataList from "@patternfly/patternfly/components/DataList/data-list.css";
import PFButton from "@patternfly/patternfly/components/Button/button.css";
import AKGlobal from "../../../authentik.css";
import { customElement, html, TemplateResult } from "lit-element";
import { gettext } from "django";
import { AuthenticatorsApi, StagesApi } from "authentik-api";
import { until } from "lit-html/directives/until";
import { FlowURLManager, UserURLManager } from "../../../api/legacy";
import { DEFAULT_CONFIG } from "../../../api/Config";
import { BaseUserSettings } from "./BaseUserSettings";
import "../../../elements/buttons/ModalButton";
import "../../../elements/buttons/SpinnerButton";
import "../../../elements/forms/DeleteForm";
@customElement("ak-user-settings-authenticator-webauthn")
export class UserSettingsAuthenticatorWebAuthnDevices extends LitElement {
@property()
stageId!: string;
static get styles(): CSSResult[] {
return [PFBase, PFCard, PFButton, PFDataList, AKGlobal];
}
export class UserSettingsAuthenticatorWebAuthnDevices extends BaseUserSettings {
render(): TemplateResult {
return html`<div class="pf-c-card">
@ -39,7 +31,7 @@ export class UserSettingsAuthenticatorWebAuthnDevices extends LitElement {
<div class="pf-c-data-list__cell">
<ak-modal-button href="${UserURLManager.authenticatorWebauthn(`devices/${device.pk}/update/`)}">
<ak-spinner-button slot="trigger" class="pf-m-primary">
${gettext('Update')}
${gettext("Update")}
</ak-spinner-button>
<div slot="modal"></div>
</ak-modal-button>
@ -64,9 +56,9 @@ export class UserSettingsAuthenticatorWebAuthnDevices extends LitElement {
</ul>
</div>
<div class="pf-c-card__footer">
${until(new StagesApi(DEFAULT_CONFIG).stagesAuthenticatorWebauthnRead({stageUuid: this.stageId}).then((stage) => {
${until(new StagesApi(DEFAULT_CONFIG).stagesAuthenticatorWebauthnRead({ stageUuid: this.objectId}).then((stage) => {
if (stage.configureFlow) {
return html`<a href="${FlowURLManager.configure(stage.pk || "", '?next=/%23user')}"
return html`<a href="${FlowURLManager.configure(stage.pk || "", "?next=/%23%2Fuser")}"
class="pf-c-button pf-m-primary">${gettext("Configure WebAuthn")}
</a>`;
}

View File

@ -0,0 +1,25 @@
import { customElement, html, TemplateResult } from "lit-element";
import { gettext } from "django";
import { FlowURLManager } from "../../../api/legacy";
import { BaseUserSettings } from "./BaseUserSettings";
@customElement("ak-user-settings-password")
export class UserSettingsPassword extends BaseUserSettings {
render(): TemplateResult {
// For this stage we don't need to check for a configureFlow,
// as the stage won't return any UI Elements if no configureFlow is set.
return html`<div class="pf-c-card">
<div class="pf-c-card__title">
${gettext("Change your password")}
</div>
<div class="pf-c-card__body">
<a href="${FlowURLManager.configure(this.objectId, "?next=/%23%2Fuser")}"
class="pf-c-button pf-m-primary">
${gettext("Change password")}
</a>
</div>
</div>`;
}
}