stages/identification: implement challenge

This commit is contained in:
Jens Langhammer 2021-02-20 18:28:11 +01:00
parent 672b86ef88
commit a1a3d316e3
9 changed files with 48 additions and 43 deletions

View File

@ -1,3 +1,5 @@
from authentik.flows.transfer.common import DataclassEncoder
from dataclasses import asdict, is_dataclass
from enum import Enum from enum import Enum
from json.encoder import JSONEncoder from json.encoder import JSONEncoder
@ -25,13 +27,6 @@ class ChallengeResponse(Serializer):
pass pass
class ChallengeEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.value
return super().default(obj)
class HttpChallengeResponse(JsonResponse): class HttpChallengeResponse(JsonResponse):
def __init__(self, challenge: Challenge, **kwargs) -> None: def __init__(self, challenge: Challenge, **kwargs) -> None:
super().__init__(challenge.data, encoder=ChallengeEncoder, **kwargs) super().__init__(challenge.data, encoder=DataclassEncoder, **kwargs)

View File

@ -61,7 +61,7 @@ class ChallengeStageView(StageView):
return HttpChallengeResponse(challenge) return HttpChallengeResponse(challenge)
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
challenge = self.response_class(data=request.POST) challenge: ChallengeResponse = self.response_class(data=request.POST)
if not challenge.is_valid(): if not challenge.is_valid():
return self.challenge_invalid(challenge) return self.challenge_invalid(challenge)
return self.challenge_valid(challenge) return self.challenge_valid(challenge)

View File

@ -1,5 +1,6 @@
"""transfer common classes""" """transfer common classes"""
from dataclasses import asdict, dataclass, field, is_dataclass from dataclasses import asdict, dataclass, field, is_dataclass
from enum import Enum
from typing import Any from typing import Any
from uuid import UUID from uuid import UUID
@ -74,6 +75,8 @@ class DataclassEncoder(DjangoJSONEncoder):
return asdict(o) return asdict(o)
if isinstance(o, UUID): if isinstance(o, UUID):
return str(o) return str(o)
if isinstance(o, Enum):
return o.value
return super().default(o) # pragma: no cover return super().default(o) # pragma: no cover

View File

@ -34,6 +34,8 @@ class IdentificationChallengeResponse(ChallengeResponse):
class IdentificationStageView(ChallengeStageView): class IdentificationStageView(ChallengeStageView):
"""Form to identify the user""" """Form to identify the user"""
response_class = IdentificationChallengeResponse
def get_user(self, uid_value: str) -> Optional[User]: def get_user(self, uid_value: str) -> Optional[User]:
"""Find user instance. Returns None if no user was found.""" """Find user instance. Returns None if no user was found."""
current_stage: IdentificationStage = self.executor.current_stage current_stage: IdentificationStage = self.executor.current_stage
@ -96,7 +98,7 @@ class IdentificationStageView(ChallengeStageView):
user_identifier = challenge.data.get("uid_field") user_identifier = challenge.data.get("uid_field")
pre_user = self.get_user(user_identifier) pre_user = self.get_user(user_identifier)
if not pre_user: if not pre_user:
LOGGER.debug("invalid_login") LOGGER.debug("invalid_login", identifier=user_identifier)
messages.error(self.request, _("Failed to authenticate.")) messages.error(self.request, _("Failed to authenticate."))
return self.challenge_invalid(challenge) return self.challenge_invalid(challenge)
self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = pre_user self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = pre_user

View File

@ -47,7 +47,7 @@ export class AdminLoginsChart extends LitElement {
level_tag: "error", level_tag: "error",
message: "Unexpected error" message: "Unexpected error"
}); });
console.log(e); console.error(e);
}) })
.then((r) => { .then((r) => {
const canvas = <HTMLCanvasElement>this.shadowRoot?.querySelector("canvas"); const canvas = <HTMLCanvasElement>this.shadowRoot?.querySelector("canvas");

View File

@ -19,7 +19,6 @@ export class Expand extends LitElement {
} }
render(): TemplateResult { render(): TemplateResult {
console.log(this.expanded);
return html`<div class="pf-c-expandable-section ${this.expanded ? "pf-m-expanded" : ""}"> return html`<div class="pf-c-expandable-section ${this.expanded ? "pf-m-expanded" : ""}">
<button type="button" class="pf-c-expandable-section__toggle" aria-expanded="${this.expanded}" @click=${() => { <button type="button" class="pf-c-expandable-section__toggle" aria-expanded="${this.expanded}" @click=${() => {
this.expanded = !this.expanded; this.expanded = !this.expanded;

View File

@ -108,7 +108,7 @@ export class ModalButton extends LitElement {
level_tag: "error", level_tag: "error",
message: "Unexpected error" message: "Unexpected error"
}); });
console.log(e); console.error(e);
}); });
}); });
}); });
@ -136,7 +136,7 @@ export class ModalButton extends LitElement {
level_tag: "error", level_tag: "error",
message: "Unexpected error" message: "Unexpected error"
}); });
console.log(e); console.error(e);
}); });
} }
} }

View File

@ -7,12 +7,18 @@ export interface IdentificationStageArgs {
input_type: string; input_type: string;
primary_action: string; primary_action: string;
sources: string[]; sources: UILoginButton[];
application_pre?: string; application_pre?: string;
} }
export interface UILoginButton {
name: string;
url: string;
icon_url?: string;
}
@customElement("ak-stage-identification") @customElement("ak-stage-identification")
export class IdentificationStage extends BaseStage { export class IdentificationStage extends BaseStage {
@ -23,6 +29,24 @@ export class IdentificationStage extends BaseStage {
return COMMON_STYLES; return COMMON_STYLES;
} }
submit(e: Event): void {
e.preventDefault();
const form = new FormData(this.shadowRoot?.querySelector("form") || undefined);
this.host?.submit(form);
}
renderSource(source: UILoginButton): TemplateResult {
let icon = html`<i class="pf-icon pf-icon-arrow" title="${source.name}"></i>`;
if (source.icon_url) {
icon = html`<img src="${source.icon_url}" alt="${source.name}">`;
}
return html`<li class="pf-c-login__main-footer-links-item">
<a href="${source.url}" class="pf-c-login__main-footer-links-item-link">
${icon}
</a>
</li>`;
}
render(): TemplateResult { render(): TemplateResult {
if (!this.args) { if (!this.args) {
return html`<ak-loading-state></ak-loading-state>`; return html`<ak-loading-state></ak-loading-state>`;
@ -33,7 +57,7 @@ export class IdentificationStage extends BaseStage {
</h1> </h1>
</header> </header>
<div class="pf-c-login__main-body"> <div class="pf-c-login__main-body">
<form class="pf-c-form"> <form class="pf-c-form" @submit=${(e) => {this.submit(e)}}>
${this.args.application_pre ? ${this.args.application_pre ?
html`<p> html`<p>
${gettext(`Login to continue to ${this.args.application_pre}.`)} ${gettext(`Login to continue to ${this.args.application_pre}.`)}
@ -41,19 +65,15 @@ export class IdentificationStage extends BaseStage {
html``} html``}
<div class="pf-c-form__group"> <div class="pf-c-form__group">
<label class="pf-c-form__label" for="uid_field-0"> <label class="pf-c-form__label">
<span class="pf-c-form__label-text">${gettext("Email or Username")}</span> <span class="pf-c-form__label-text">${gettext("Email or Username")}</span>
<span class="pf-c-form__label-required" aria-hidden="true">*</span> <span class="pf-c-form__label-required" aria-hidden="true">*</span>
</label> </label>
<input type="text" name="uid_field" placeholder="Email or Username" autofocus autocomplete="username" class="pf-c-form-control" required="" id="id_uid_field"> <input type="text" name="uid_field" placeholder="Email or Username" autofocus autocomplete="username" class="pf-c-form-control" required="">
</div> </div>
<div class="pf-c-form__group pf-m-action"> <div class="pf-c-form__group pf-m-action">
<button class="pf-c-button pf-m-primary pf-m-block" @click=${(e: Event) => { <button type="submit" class="pf-c-button pf-m-primary pf-m-block">
e.preventDefault();
const form = new FormData(this.shadowRoot.querySelector("form"));
this.host?.submit(form);
}}>
${this.args.primary_action} ${this.args.primary_action}
</button> </button>
</div> </div>
@ -61,26 +81,12 @@ export class IdentificationStage extends BaseStage {
</div> </div>
<footer class="pf-c-login__main-footer"> <footer class="pf-c-login__main-footer">
<ul class="pf-c-login__main-footer-links"> <ul class="pf-c-login__main-footer-links">
${this.args.sources.map(() => { ${this.args.sources.map((source) => {
// TODO: source testing return this.renderSource(source);
// TODO: Placeholder and label for input above
return html``;
// {% for source in sources %}
// <li class="pf-c-login__main-footer-links-item">
// <a href="{{ source.url }}" class="pf-c-login__main-footer-links-item-link">
// {% if source.icon_path %}
// <img src="{% static source.icon_path %}" style="width:24px;" alt="{{ source.name }}">
// {% elif source.icon_url %}
// <img src="icon_url" alt="{{ source.name }}">
// {% else %}
// <i class="pf-icon pf-icon-arrow" title="{{ source.name }}"></i>
// {% endif %}
// </a>
// </li>
// {% endfor %}
})} })}
</ul> </ul>
{% if enroll_url or recovery_url %}
<!--{% if enroll_url or recovery_url %}
<div class="pf-c-login__main-footer-band"> <div class="pf-c-login__main-footer-band">
{% if enroll_url %} {% if enroll_url %}
<p class="pf-c-login__main-footer-band-item"> <p class="pf-c-login__main-footer-band-item">
@ -94,7 +100,7 @@ export class IdentificationStage extends BaseStage {
</p> </p>
{% endif %} {% endif %}
</div> </div>
{% endif %} {% endif %}-->
</footer>`; </footer>`;
} }

View File

@ -138,7 +138,7 @@ export class SiteShell extends LitElement {
level_tag: "error", level_tag: "error",
message: "Unexpected error" message: "Unexpected error"
}); });
console.log(e); console.error(e);
}); });
}); });
}); });