Skip to content

Commit

Permalink
add friendlier error messages to Captcha stage
Browse files Browse the repository at this point in the history
  • Loading branch information
gergosimonyi committed Oct 22, 2024
1 parent 1a0ef46 commit 2327931
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions authentik/stages/captcha/stage.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""authentik captcha stage"""

from django.http.response import HttpResponse
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext as _
from requests import RequestException
from rest_framework.fields import CharField
from rest_framework.serializers import ValidationError
Expand All @@ -27,6 +27,22 @@ class CaptchaChallenge(WithUserInfoChallenge):
component = CharField(default="ak-stage-captcha")


def get_friendly_captcha_error(error: str) -> str:
match error:
case "missing-input-secret":
return _("Secret was not provided. This is likely a misconfiguration error.")
case "invalid-input-secret":
return _("Secret was invalid. This is likely a misconfiguration error.")
case "missing-input-response":
return _("Client response was not provided. Try again.")
case "invalid-input-response":
return _("Client response was invalid. Try again.")
case "timeout-or-duplicate":
return _("Client response has timed out or was already used. Try again.")

Check warning on line 41 in authentik/stages/captcha/stage.py

View check run for this annotation

Codecov / codecov/patch

authentik/stages/captcha/stage.py#L31-L41

Added lines #L31 - L41 were not covered by tests

return _("Unknown error")

Check warning on line 43 in authentik/stages/captcha/stage.py

View check run for this annotation

Codecov / codecov/patch

authentik/stages/captcha/stage.py#L43

Added line #L43 was not covered by tests


def verify_captcha_token(stage: CaptchaStage, token: str, remote_ip: str):
"""Validate captcha token"""
try:
Expand All @@ -45,10 +61,11 @@ def verify_captcha_token(stage: CaptchaStage, token: str, remote_ip: str):
data = response.json()
if stage.error_on_invalid_score:
if not data.get("success", False):
error_codes = data.get("error-codes")
raise ValidationError(

Check warning on line 65 in authentik/stages/captcha/stage.py

View check run for this annotation

Codecov / codecov/patch

authentik/stages/captcha/stage.py#L60-L65

Added lines #L60 - L65 were not covered by tests
_(
"Failed to validate token: {error}".format(
error=data.get("error-codes", _("Unknown error"))
"Invalid captcha response: {error}".format(
error="".join(map(get_friendly_captcha_error, error_codes))
)
)
)
Expand Down

0 comments on commit 2327931

Please sign in to comment.