stages/authenticator_static: migrate to SPA

This commit is contained in:
Jens Langhammer 2021-02-21 19:34:49 +01:00
parent 21afda6dc2
commit 6df89e7abf
5 changed files with 109 additions and 37 deletions

View File

@ -1,31 +1,9 @@
"""Static Authenticator forms""" """Static Authenticator forms"""
from django import forms from django import forms
from django.utils.safestring import mark_safe
from authentik.stages.authenticator_static.models import AuthenticatorStaticStage from authentik.stages.authenticator_static.models import AuthenticatorStaticStage
class StaticTokenWidget(forms.widgets.Widget):
"""Widget to render tokens as multiple labels"""
def render(self, name, value, attrs=None, renderer=None):
final_string = '<ul class="ak-otp-tokens">'
for token in value:
final_string += f"<li>{token.token}</li>"
final_string += "</ul>"
return mark_safe(final_string) # nosec
class SetupForm(forms.Form):
"""Form to setup Static OTP"""
tokens = forms.CharField(widget=StaticTokenWidget, disabled=True, required=False)
def __init__(self, tokens, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["tokens"].initial = tokens
class AuthenticatorStaticStageForm(forms.ModelForm): class AuthenticatorStaticStageForm(forms.ModelForm):
"""Static Authenticator Stage setup form""" """Static Authenticator Stage setup form"""

View File

@ -1,14 +1,16 @@
"""Static OTP Setup stage""" """Static OTP Setup stage"""
from typing import Any
from django.http import HttpRequest, HttpResponse from django.http import HttpRequest, HttpResponse
from django.views.generic import FormView
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from rest_framework.fields import CharField, IntegerField, ListField
from structlog.stdlib import get_logger from structlog.stdlib import get_logger
from authentik.flows.challenge import (
ChallengeResponse,
ChallengeTypes,
WithUserInfoChallenge,
)
from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER
from authentik.flows.stage import StageView from authentik.flows.stage import ChallengeStageView
from authentik.stages.authenticator_static.forms import SetupForm
from authentik.stages.authenticator_static.models import AuthenticatorStaticStage from authentik.stages.authenticator_static.models import AuthenticatorStaticStage
LOGGER = get_logger() LOGGER = get_logger()
@ -16,16 +18,24 @@ SESSION_STATIC_DEVICE = "static_device"
SESSION_STATIC_TOKENS = "static_device_tokens" SESSION_STATIC_TOKENS = "static_device_tokens"
class AuthenticatorStaticStageView(FormView, StageView): class AuthenticatorStaticChallenge(WithUserInfoChallenge):
"""Static authenticator challenge"""
codes = ListField(child=CharField())
class AuthenticatorStaticStageView(ChallengeStageView):
"""Static OTP Setup stage""" """Static OTP Setup stage"""
form_class = SetupForm def get_challenge(self, *args, **kwargs) -> AuthenticatorStaticChallenge:
tokens: list[StaticToken] = self.request.session[SESSION_STATIC_TOKENS]
def get_form_kwargs(self, **kwargs) -> dict[str, Any]: return AuthenticatorStaticChallenge(
kwargs = super().get_form_kwargs(**kwargs) data={
tokens = self.request.session[SESSION_STATIC_TOKENS] "type": ChallengeTypes.native,
kwargs["tokens"] = tokens "component": "ak-stage-authenticator-static",
return kwargs "codes": [token.token for token in tokens],
}
)
def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
user = self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER) user = self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER)
@ -51,7 +61,7 @@ class AuthenticatorStaticStageView(FormView, StageView):
self.request.session[SESSION_STATIC_TOKENS] = tokens self.request.session[SESSION_STATIC_TOKENS] = tokens
return super().get(request, *args, **kwargs) return super().get(request, *args, **kwargs)
def form_valid(self, form: SetupForm) -> HttpResponse: def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
"""Verify OTP Token""" """Verify OTP Token"""
device: StaticDevice = self.request.session[SESSION_STATIC_DEVICE] device: StaticDevice = self.request.session[SESSION_STATIC_DEVICE]
device.save() device.save()

View File

@ -0,0 +1,80 @@
import { gettext } from "django";
import { css, CSSResult, customElement, html, property, TemplateResult } from "lit-element";
import { WithUserInfoChallenge } from "../../../api/Flows";
import { COMMON_STYLES } from "../../../common/styles";
import { BaseStage } from "../base";
export interface AuthenticatorStaticChallenge extends WithUserInfoChallenge {
codes: number[];
}
@customElement("ak-stage-authenticator-static")
export class AuthenticatorStaticStage extends BaseStage {
@property({ attribute: false })
challenge?: AuthenticatorStaticChallenge;
static get styles(): CSSResult[] {
return COMMON_STYLES.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;
}
`);
}
render(): TemplateResult {
if (!this.challenge) {
return html`<ak-loading-state></ak-loading-state>`;
}
return html`<header class="pf-c-login__main-header">
<h1 class="pf-c-title pf-m-3xl">
${this.challenge.title}
</h1>
</header>
<div class="pf-c-login__main-body">
<form class="pf-c-form" @submit=${(e: Event) => { this.submit(e); }}>
<div class="pf-c-form__group">
<div class="form-control-static">
<div class="left">
<img class="pf-c-avatar" src="${this.challenge.pending_user_avatar}" alt="${gettext("User's avatar")}">
${this.challenge.pending_user}
</div>
<div class="right">
<a href="/-/cancel/">${gettext("Not you?")}</a>
</div>
</div>
</div>
<ak-form-element
label="${gettext("Tokens")}"
?required="${true}"
class="pf-c-form__group">
<ul class="ak-otp-tokens">
${this.challenge.codes.map((token) => {
return html`<li>${token}</li>`;
})}
</ul>
</ak-form-element>
<div class="pf-c-form__group pf-m-action">
<button type="submit" class="pf-c-button pf-m-primary pf-m-block">
${gettext("Continue")}
</button>
</div>
</form>
</div>
<footer class="pf-c-login__main-footer">
<ul class="pf-c-login__main-footer-links">
</ul>
</footer>`;
}
}

View File

@ -3,7 +3,7 @@ import { CSSResult, customElement, html, property, TemplateResult } from "lit-el
import { WithUserInfoChallenge } from "../../../api/Flows"; import { WithUserInfoChallenge } from "../../../api/Flows";
import { COMMON_STYLES } from "../../../common/styles"; import { COMMON_STYLES } from "../../../common/styles";
import { BaseStage } from "../base"; import { BaseStage } from "../base";
import 'webcomponent-qr-code' import "webcomponent-qr-code";
export interface AuthenticatorTOTPChallenge extends WithUserInfoChallenge { export interface AuthenticatorTOTPChallenge extends WithUserInfoChallenge {
config_url: string; config_url: string;

View File

@ -9,6 +9,7 @@ import "../../elements/stages/email/EmailStage";
import "../../elements/stages/autosubmit/AutosubmitStage"; import "../../elements/stages/autosubmit/AutosubmitStage";
import "../../elements/stages/prompt/PromptStage"; import "../../elements/stages/prompt/PromptStage";
import "../../elements/stages/authenticator_totp/AuthenticatorTOTPStage"; import "../../elements/stages/authenticator_totp/AuthenticatorTOTPStage";
import "../../elements/stages/authenticator_static/AuthenticatorStaticStage";
import { ShellChallenge, Challenge, ChallengeTypes, Flow, RedirectChallenge } from "../../api/Flows"; import { ShellChallenge, Challenge, ChallengeTypes, Flow, RedirectChallenge } from "../../api/Flows";
import { DefaultClient } from "../../api/Client"; import { DefaultClient } from "../../api/Client";
import { IdentificationChallenge } from "../../elements/stages/identification/IdentificationStage"; import { IdentificationChallenge } from "../../elements/stages/identification/IdentificationStage";
@ -18,6 +19,7 @@ import { EmailChallenge } from "../../elements/stages/email/EmailStage";
import { AutosubmitChallenge } from "../../elements/stages/autosubmit/AutosubmitStage"; import { AutosubmitChallenge } from "../../elements/stages/autosubmit/AutosubmitStage";
import { PromptChallenge } from "../../elements/stages/prompt/PromptStage"; import { PromptChallenge } from "../../elements/stages/prompt/PromptStage";
import { AuthenticatorTOTPChallenge } from "../../elements/stages/authenticator_totp/AuthenticatorTOTPStage"; import { AuthenticatorTOTPChallenge } from "../../elements/stages/authenticator_totp/AuthenticatorTOTPStage";
import { AuthenticatorStaticChallenge } from "../../elements/stages/authenticator_static/AuthenticatorStaticStage";
@customElement("ak-flow-executor") @customElement("ak-flow-executor")
export class FlowExecutor extends LitElement { export class FlowExecutor extends LitElement {
@ -128,6 +130,8 @@ export class FlowExecutor extends LitElement {
return html`<ak-stage-prompt .host=${this} .challenge=${this.challenge as PromptChallenge}></ak-stage-prompt>`; return html`<ak-stage-prompt .host=${this} .challenge=${this.challenge as PromptChallenge}></ak-stage-prompt>`;
case "ak-stage-authenticator-totp": case "ak-stage-authenticator-totp":
return html`<ak-stage-authenticator-totp .host=${this} .challenge=${this.challenge as AuthenticatorTOTPChallenge}></ak-stage-authenticator-totp>`; return html`<ak-stage-authenticator-totp .host=${this} .challenge=${this.challenge as AuthenticatorTOTPChallenge}></ak-stage-authenticator-totp>`;
case "ak-stage-authenticator-static":
return html`<ak-stage-authenticator-static .host=${this} .challenge=${this.challenge as AuthenticatorStaticChallenge}></ak-stage-authenticator-static>`;
default: default:
break; break;
} }