stages/captcha: migrated to SPA
This commit is contained in:
parent
890e0e9054
commit
9e6a7bf16b
|
@ -1,16 +1,9 @@
|
|||
"""authentik captcha stage forms"""
|
||||
from captcha.fields import ReCaptchaField
|
||||
from django import forms
|
||||
|
||||
from authentik.stages.captcha.models import CaptchaStage
|
||||
|
||||
|
||||
class CaptchaForm(forms.Form):
|
||||
"""authentik captcha stage form"""
|
||||
|
||||
captcha = ReCaptchaField()
|
||||
|
||||
|
||||
class CaptchaStageForm(forms.ModelForm):
|
||||
"""Form to edit CaptchaStage Instance"""
|
||||
|
||||
|
|
|
@ -1,24 +1,73 @@
|
|||
"""authentik captcha stage"""
|
||||
|
||||
from django.views.generic import FormView
|
||||
from django.http.response import HttpResponse
|
||||
from requests import RequestException, post
|
||||
from rest_framework.fields import CharField
|
||||
from rest_framework.serializers import ValidationError
|
||||
|
||||
from authentik.flows.stage import StageView
|
||||
from authentik.stages.captcha.forms import CaptchaForm
|
||||
from authentik import __version__
|
||||
from authentik.flows.challenge import (
|
||||
Challenge,
|
||||
ChallengeResponse,
|
||||
ChallengeTypes,
|
||||
WithUserInfoChallenge,
|
||||
)
|
||||
from authentik.flows.stage import ChallengeStageView
|
||||
from authentik.lib.utils.http import get_client_ip
|
||||
from authentik.stages.captcha.models import CaptchaStage
|
||||
|
||||
|
||||
class CaptchaStageView(FormView, StageView):
|
||||
class CaptchaChallenge(WithUserInfoChallenge):
|
||||
"""Site public key"""
|
||||
|
||||
site_key = CharField()
|
||||
|
||||
|
||||
class CaptchaChallengeResponse(ChallengeResponse):
|
||||
"""Validate captcha token"""
|
||||
|
||||
token = CharField()
|
||||
|
||||
def validate_token(self, token: str) -> str:
|
||||
"""Validate captcha token"""
|
||||
stage: CaptchaStage = self.stage.executor.current_stage
|
||||
try:
|
||||
response = post(
|
||||
"https://www.google.com/recaptcha/api/siteverify",
|
||||
headers={
|
||||
"Content-type": "application/x-www-form-urlencoded",
|
||||
"User-agent": f"authentik {__version__} ReCaptcha",
|
||||
},
|
||||
data={
|
||||
"secret": stage.private_key,
|
||||
"response": token,
|
||||
"remoteip": get_client_ip(self.stage.request),
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
if not data.get("success", False):
|
||||
raise ValidationError(
|
||||
f"Failed to validate token: {data.get('error-codes', '')}"
|
||||
)
|
||||
except RequestException as exc:
|
||||
raise ValidationError("Failed to validate token") from exc
|
||||
return token
|
||||
|
||||
|
||||
class CaptchaStageView(ChallengeStageView):
|
||||
"""Simple captcha checker, logic is handeled in django-captcha module"""
|
||||
|
||||
form_class = CaptchaForm
|
||||
response_class = CaptchaChallengeResponse
|
||||
|
||||
def form_valid(self, form):
|
||||
def get_challenge(self, *args, **kwargs) -> Challenge:
|
||||
return CaptchaChallenge(
|
||||
data={
|
||||
"type": ChallengeTypes.native,
|
||||
"component": "ak-stage-captcha",
|
||||
"site_key": self.executor.current_stage.public_key,
|
||||
}
|
||||
)
|
||||
|
||||
def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
|
||||
return self.executor.stage_ok()
|
||||
|
||||
def get_form(self, form_class=None):
|
||||
form = CaptchaForm(**self.get_form_kwargs())
|
||||
form.fields["captcha"].public_key = self.executor.current_stage.public_key
|
||||
form.fields["captcha"].private_key = self.executor.current_stage.private_key
|
||||
form.fields["captcha"].widget.attrs["data-sitekey"] = form.fields[
|
||||
"captcha"
|
||||
].public_key
|
||||
return form
|
||||
|
|
|
@ -46,7 +46,7 @@ class TestCaptchaStage(TestCase):
|
|||
reverse(
|
||||
"authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}
|
||||
),
|
||||
{"g-recaptcha-response": "PASSED"},
|
||||
{"token": "PASSED"},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertJSONEqual(
|
||||
|
|
|
@ -8249,6 +8249,7 @@ definitions:
|
|||
title: Avatar
|
||||
type: string
|
||||
readOnly: true
|
||||
minLength: 1
|
||||
attributes:
|
||||
title: Attributes
|
||||
type: object
|
||||
|
|
5
web/package-lock.json
generated
5
web/package-lock.json
generated
|
@ -301,6 +301,11 @@
|
|||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"@types/grecaptcha": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/grecaptcha/-/grecaptcha-3.0.1.tgz",
|
||||
"integrity": "sha512-eMA/2quQoxwSe8oOBB1H6KNXNqginzt9BHAt2vVVUoQswZNct2QwSAmEMsN/VHj/XSNxM3p+Py15B7omEaAC9w=="
|
||||
},
|
||||
"@types/html-minifier": {
|
||||
"version": "3.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/html-minifier/-/html-minifier-3.5.3.tgz",
|
||||
|
|
|
@ -16,6 +16,7 @@
|
|||
"@sentry/tracing": "^6.2.0",
|
||||
"@types/chart.js": "^2.9.30",
|
||||
"@types/codemirror": "0.0.108",
|
||||
"@types/grecaptcha": "^3.0.1",
|
||||
"base64-js": "^1.5.1",
|
||||
"chart.js": "^2.9.4",
|
||||
"codemirror": "^5.59.3",
|
||||
|
|
87
web/src/elements/stages/captcha/CaptchaStage.ts
Normal file
87
web/src/elements/stages/captcha/CaptchaStage.ts
Normal file
|
@ -0,0 +1,87 @@
|
|||
import { gettext } from "django";
|
||||
import { CSSResult, customElement, html, property, TemplateResult } from "lit-element";
|
||||
import { WithUserInfoChallenge } from "../../../api/Flows";
|
||||
import { COMMON_STYLES } from "../../../common/styles";
|
||||
import { SpinnerSize } from "../../Spinner";
|
||||
import { BaseStage } from "../base";
|
||||
import "../form";
|
||||
|
||||
export interface CaptchaChallenge extends WithUserInfoChallenge {
|
||||
site_key: string;
|
||||
}
|
||||
|
||||
@customElement("ak-stage-captcha")
|
||||
export class CaptchaStage extends BaseStage {
|
||||
|
||||
@property({ attribute: false })
|
||||
challenge?: CaptchaChallenge;
|
||||
|
||||
static get styles(): CSSResult[] {
|
||||
return COMMON_STYLES;
|
||||
}
|
||||
|
||||
submitFormAlt(token: string): void {
|
||||
const form = new FormData();
|
||||
form.set("token", token);
|
||||
this.host?.submit(form);
|
||||
}
|
||||
|
||||
firstUpdated(): void {
|
||||
const script = document.createElement("script");
|
||||
script.src = "https://www.google.com/recaptcha/api.js";//?render=${this.challenge?.site_key}`;
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
const captchaContainer = document.createElement("div");
|
||||
document.body.appendChild(captchaContainer);
|
||||
script.onload = () => {
|
||||
console.debug("authentik/stages/captcha: script loaded");
|
||||
grecaptcha.ready(() => {
|
||||
if (!this.challenge?.site_key) return;
|
||||
console.debug("authentik/stages/captcha: ready");
|
||||
const captchaId = grecaptcha.render(captchaContainer, {
|
||||
sitekey: this.challenge.site_key,
|
||||
callback: (token) => {
|
||||
this.submitFormAlt(token);
|
||||
},
|
||||
size: "invisible",
|
||||
});
|
||||
grecaptcha.execute(captchaId);
|
||||
});
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
|
||||
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">
|
||||
<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="/flows/-/cancel/">${gettext("Not you?")}</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ak-loading">
|
||||
<ak-spinner size=${SpinnerSize.XLarge}></ak-spinner>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<footer class="pf-c-login__main-footer">
|
||||
<ul class="pf-c-login__main-footer-links">
|
||||
</ul>
|
||||
</footer>`;
|
||||
}
|
||||
|
||||
}
|
|
@ -14,10 +14,6 @@ export class LibraryApplication extends LitElement {
|
|||
static get styles(): CSSResult[] {
|
||||
return COMMON_STYLES.concat(
|
||||
css`
|
||||
:host,
|
||||
main {
|
||||
height: 100%;
|
||||
}
|
||||
a {
|
||||
height: 100%;
|
||||
}
|
||||
|
@ -59,7 +55,12 @@ export class LibraryPage extends LitElement {
|
|||
apps?: AKResponse<Application>;
|
||||
|
||||
static get styles(): CSSResult[] {
|
||||
return COMMON_STYLES;
|
||||
return COMMON_STYLES.concat(css`
|
||||
:host,
|
||||
main {
|
||||
height: 100%;
|
||||
}
|
||||
`);
|
||||
}
|
||||
|
||||
firstUpdated(): void {
|
||||
|
|
|
@ -2,16 +2,17 @@ import { gettext } from "django";
|
|||
import { LitElement, html, customElement, property, TemplateResult, CSSResult, css } from "lit-element";
|
||||
import { unsafeHTML } from "lit-html/directives/unsafe-html";
|
||||
import { getCookie } from "../../utils";
|
||||
import "../../elements/stages/identification/IdentificationStage";
|
||||
import "../../elements/stages/password/PasswordStage";
|
||||
import "../../elements/stages/authenticator_static/AuthenticatorStaticStage";
|
||||
import "../../elements/stages/authenticator_totp/AuthenticatorTOTPStage";
|
||||
import "../../elements/stages/authenticator_validate/AuthenticatorValidateStage";
|
||||
import "../../elements/stages/authenticator_webauthn/WebAuthnAuthenticatorRegisterStage";
|
||||
import "../../elements/stages/autosubmit/AutosubmitStage";
|
||||
import "../../elements/stages/captcha/CaptchaStage";
|
||||
import "../../elements/stages/consent/ConsentStage";
|
||||
import "../../elements/stages/email/EmailStage";
|
||||
import "../../elements/stages/autosubmit/AutosubmitStage";
|
||||
import "../../elements/stages/identification/IdentificationStage";
|
||||
import "../../elements/stages/password/PasswordStage";
|
||||
import "../../elements/stages/prompt/PromptStage";
|
||||
import "../../elements/stages/authenticator_totp/AuthenticatorTOTPStage";
|
||||
import "../../elements/stages/authenticator_static/AuthenticatorStaticStage";
|
||||
import "../../elements/stages/authenticator_webauthn/WebAuthnAuthenticatorRegisterStage";
|
||||
import "../../elements/stages/authenticator_validate/AuthenticatorValidateStage";
|
||||
import { ShellChallenge, Challenge, ChallengeTypes, Flow, RedirectChallenge } from "../../api/Flows";
|
||||
import { DefaultClient } from "../../api/Client";
|
||||
import { IdentificationChallenge } from "../../elements/stages/identification/IdentificationStage";
|
||||
|
@ -24,6 +25,7 @@ import { AuthenticatorTOTPChallenge } from "../../elements/stages/authenticator_
|
|||
import { AuthenticatorStaticChallenge } from "../../elements/stages/authenticator_static/AuthenticatorStaticStage";
|
||||
import { AuthenticatorValidateStageChallenge } from "../../elements/stages/authenticator_validate/AuthenticatorValidateStage";
|
||||
import { WebAuthnAuthenticatorRegisterChallenge } from "../../elements/stages/authenticator_webauthn/WebAuthnAuthenticatorRegisterStage";
|
||||
import { CaptchaChallenge } from "../../elements/stages/captcha/CaptchaStage";
|
||||
import { COMMON_STYLES } from "../../common/styles";
|
||||
import { SpinnerSize } from "../../elements/Spinner";
|
||||
import { StageHost } from "../../elements/stages/base";
|
||||
|
@ -149,6 +151,8 @@ export class FlowExecutor extends LitElement implements StageHost {
|
|||
return html`<ak-stage-identification .host=${this} .challenge=${this.challenge as IdentificationChallenge}></ak-stage-identification>`;
|
||||
case "ak-stage-password":
|
||||
return html`<ak-stage-password .host=${this} .challenge=${this.challenge as PasswordChallenge}></ak-stage-password>`;
|
||||
case "ak-stage-captcha":
|
||||
return html`<ak-stage-captcha .host=${this} .challenge=${this.challenge as CaptchaChallenge}></ak-stage-captcha>`;
|
||||
case "ak-stage-consent":
|
||||
return html`<ak-stage-consent .host=${this} .challenge=${this.challenge as ConsentChallenge}></ak-stage-consent>`;
|
||||
case "ak-stage-email":
|
||||
|
|
Reference in a new issue