Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ Progression requirements can now reference the top of the prescribed range via t
every other source.
* Workout logs have an optional `notes` field, so individual sets can get a note
(e.g. form cues or how the set felt) in addition to the notes of the session.
* Cloudflare Turnstile can be used as captcha on the registration and password
reset forms, as an alternative to Google reCAPTCHA. The `CAPTCHA_PROVIDER`
setting selects reCAPTCHA, Turnstile or no captcha, see the settings page in
the docs.

### Bug fixes

Expand All @@ -42,7 +46,9 @@ Progression requirements can now reference the top of the prescribed range via t
## New settings
*(for self-hoster)*

* ...
* `CAPTCHA_PROVIDER` (`none`, `recaptcha` or `turnstile`) replaces `USE_RECAPTCHA`.
`USE_RECAPTCHA=True` keeps working for now, but `manage.py check` warns about
it. Turnstile needs `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`.

## Breaking API changes
*(only relevant if you have your own scripts or interact with the REST API)*
Expand Down
2 changes: 2 additions & 0 deletions settings/ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@
RECAPTCHA_PRIVATE_KEY = ''
USE_RECAPTCHA = False

WGER_SETTINGS['CAPTCHA_PROVIDER'] = 'none'

# Test-only RSA keypair for JWT, safe to commit.
JWT_PRIVATE_KEY = (
'eyJhbGciOiAiUlMyNTYiLCAia3R5IjogIlJTQSIsICJuIjogIjlSbXdqZDJadG9DUzg4N0hNY2JpNFpK'
Expand Down
7 changes: 7 additions & 0 deletions settings/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@
RECAPTCHA_PRIVATE_KEY = env.str('RECAPTCHA_PRIVATE_KEY', '')
RECAPTCHA_REQUIRED_SCORE = env.float('RECAPTCHA_REQUIRED_SCORE', 0.75)

# Your Cloudflare Turnstile keys
TURNSTILE_SITE_KEY = env.str('TURNSTILE_SITE_KEY', '')
TURNSTILE_SECRET_KEY = env.str('TURNSTILE_SECRET_KEY', '')

# The site's URL (e.g. http://www.my-local-gym.com or http://localhost:8000)
# This is needed for uploaded files and images (exercise images, etc.) to be
# properly served.
Expand Down Expand Up @@ -192,6 +196,9 @@
)
WGER_SETTINGS['SYNC_OFF_DAILY_DELTA_CELERY'] = env.bool('SYNC_OFF_DAILY_DELTA_CELERY', False)
WGER_SETTINGS['EXPORT_INGREDIENTS_BULK_CELERY'] = env.bool('EXPORT_INGREDIENTS_BULK_CELERY', False)
# CAPTCHA_PROVIDER: 'recaptcha', 'turnstile', or 'none'
WGER_SETTINGS['CAPTCHA_PROVIDER'] = env.str('CAPTCHA_PROVIDER', 'none')
# Deprecated, USE_RECAPTCHA=True still means CAPTCHA_PROVIDER=recaptcha
WGER_SETTINGS['USE_RECAPTCHA'] = env.bool('USE_RECAPTCHA', False)
WGER_SETTINGS['USE_CELERY'] = env.bool('USE_CELERY', False)
WGER_SETTINGS['CACHE_API_EXERCISES_CELERY'] = env.bool('CACHE_API_EXERCISES_CELERY', False)
Expand Down
12 changes: 11 additions & 1 deletion settings/settings_global.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@
ACCOUNT_LOGIN_METHODS = {'username', 'email'}

# Use wger's own login/signup/password reset forms (allauth's forms + the
# password-visibility toggle, and a conditional reCAPTCHA field on signup and
# password-visibility toggle, and a conditional captcha field on signup and
# password reset).
ACCOUNT_FORMS = {
'login': 'wger.core.forms.WgerLoginForm',
Expand Down Expand Up @@ -675,6 +675,10 @@ def jwk_b64_to_pem(b64_jwk_str: str):
'TWITTER': False,
'MASTODON': 'https://fosstodon.org/@wger',
'USE_CELERY': False,
# CAPTCHA_PROVIDER: 'recaptcha', 'turnstile', or 'none'
'CAPTCHA_PROVIDER': 'none',
# Deprecated: USE_RECAPTCHA is kept for backwards compatibility
# If set to True and CAPTCHA_PROVIDER is 'none', it will use 'recaptcha'
'USE_RECAPTCHA': False,
'WGER_INSTANCE': 'https://wger.de',

Expand Down Expand Up @@ -733,6 +737,12 @@ def jwk_b64_to_pem(b64_jwk_str: str):
RECAPTCHA_PRIVATE_KEY = ''
RECAPTCHA_REQUIRED_SCORE = 0

#
# Cloudflare Turnstile
#
TURNSTILE_SITE_KEY = ''
TURNSTILE_SECRET_KEY = ''

#
# Storage options
#
Expand Down
173 changes: 173 additions & 0 deletions wger/core/captcha.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
# This file is part of wger Workout Manager <https://github.com/wger-project>.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

"""
Captcha providers for the signup and password reset forms

WGER_SETTINGS['CAPTCHA_PROVIDER'] names one of the PROVIDERS (or 'none'). A new
provider is a CaptchaProvider subclass with an entry in PROVIDERS; the forms and
the system checks only go through this module.
"""

# Standard Library
import logging

# Django
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy

# Third Party
import requests
from django_recaptcha.fields import ReCaptchaField
from django_recaptcha.widgets import ReCaptchaV3

# wger
from wger.utils.requests import wger_headers


logger = logging.getLogger(__name__)

TURNSTILE_SCRIPT_URL = 'https://challenges.cloudflare.com/turnstile/v0/api.js'
TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'


class TurnstileWidget(forms.Widget):
"""
Cloudflare's Turnstile widget, rendered implicitly by its script

The script adds the token as the hidden input cf-turnstile-response to the
surrounding form.
"""

template_name = 'forms/turnstile.html'

def __init__(self, action: str, attrs=None):
super().__init__(attrs)
self.action = action

def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
context['widget'].update(
{
'site_key': settings.TURNSTILE_SITE_KEY,
'action': self.action,
'script_url': TURNSTILE_SCRIPT_URL,
}
)
return context

def value_from_datadict(self, data, files, name):
return data.get('cf-turnstile-response')


class TurnstileField(forms.CharField):
"""
Verifies the Turnstile token with Cloudflare, rejects it if that fails
"""

default_error_messages = {
'required': gettext_lazy('The captcha could not be verified, please try again.'),
'invalid': gettext_lazy('The captcha could not be verified, please try again.'),
}

def __init__(self, action: str, **kwargs):
# Cloudflare's tokens are at most 2048 characters
super().__init__(widget=TurnstileWidget(action), max_length=2048, **kwargs)

def validate(self, value):
super().validate(value)

try:
response = requests.post(
TURNSTILE_VERIFY_URL,
data={'secret': settings.TURNSTILE_SECRET_KEY, 'response': value},
headers=wger_headers(),
timeout=10,
)
response.raise_for_status()
result = response.json()
except (requests.RequestException, ValueError) as e:
logger.warning('Turnstile verification request failed: %s', type(e).__name__)
result = None

if not isinstance(result, dict) or result.get('success') is not True:
raise ValidationError(self.error_messages['invalid'], code='invalid')


class CaptchaProvider:
"""A captcha service the forms can be secured with"""

required_settings: tuple[str, ...] = ()
"""Settings that must not be empty for the captcha to work"""

def field(self, action: str) -> forms.Field:
"""
A fresh form field; the action names the form, e.g. for the provider's statistics
"""
raise NotImplementedError

def missing_settings(self) -> list[str]:
return [name for name in self.required_settings if not getattr(settings, name, '')]


class RecaptchaProvider(CaptchaProvider):
required_settings = ('RECAPTCHA_PUBLIC_KEY', 'RECAPTCHA_PRIVATE_KEY')

def field(self, action: str) -> forms.Field:
return ReCaptchaField(
widget=ReCaptchaV3(action=action),
label='reCaptcha',
help_text=gettext_lazy('The form is secured with reCAPTCHA'),
)


class TurnstileProvider(CaptchaProvider):
required_settings = ('TURNSTILE_SITE_KEY', 'TURNSTILE_SECRET_KEY')

def field(self, action: str) -> forms.Field:
return TurnstileField(
action,
label='Turnstile',
help_text=gettext_lazy('The form is secured with Cloudflare Turnstile'),
)


PROVIDERS: dict[str, CaptchaProvider] = {
'recaptcha': RecaptchaProvider(),
'turnstile': TurnstileProvider(),
}


def captcha_provider() -> str:
"""
The configured captcha provider, 'none' or a key of PROVIDERS

The deprecated USE_RECAPTCHA=True still means 'recaptcha' when no other
provider is set.
"""
provider = settings.WGER_SETTINGS.get('CAPTCHA_PROVIDER', 'none')
if provider == 'none' and settings.WGER_SETTINGS.get('USE_RECAPTCHA'):
return 'recaptcha'
return provider


def captcha_field(action: str) -> forms.Field | None:
"""
The field for the configured captcha provider, None if there is none
"""
provider = PROVIDERS.get(captcha_provider())
return provider.field(action) if provider else None
40 changes: 40 additions & 0 deletions wger/core/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
)

# wger
from wger.core.captcha import (
PROVIDERS,
captcha_provider,
)
from wger.utils.constants import DOWNLOAD_INGREDIENT_OPTIONS


Expand Down Expand Up @@ -55,4 +59,40 @@ def settings_check(app_configs, **kwargs):
id='wger.E001',
)
)

# The captcha provider must exist and have its keys
provider_name = captcha_provider()
valid_providers = ('none', *PROVIDERS)
if provider_name not in valid_providers:
errors.append(
Error(
f"Invalid CAPTCHA_PROVIDER: '{provider_name}'",
hint=f'CAPTCHA_PROVIDER must be one of {valid_providers}',
obj=settings,
id='wger.E002',
)
)
elif provider_name != 'none':
missing = PROVIDERS[provider_name].missing_settings()
if missing:
errors.append(
Warning(
f'Captcha provider "{provider_name}" is not configured',
hint=f'Set {", ".join(missing)}, otherwise the captcha will not work.',
obj=settings,
id='wger.W004',
)
)

# USE_RECAPTCHA is deprecated, an explicit CAPTCHA_PROVIDER overrides it
if settings.WGER_SETTINGS.get('USE_RECAPTCHA'):
configured = settings.WGER_SETTINGS.get('CAPTCHA_PROVIDER', 'none')
if configured == 'none':
message = 'USE_RECAPTCHA is deprecated'
hint = 'Set CAPTCHA_PROVIDER to "recaptcha" instead and remove USE_RECAPTCHA.'
else:
message = 'USE_RECAPTCHA is ignored'
hint = f'CAPTCHA_PROVIDER "{configured}" takes precedence, remove USE_RECAPTCHA.'
errors.append(Warning(message, hint=hint, obj=settings, id='wger.W005'))

return errors
28 changes: 10 additions & 18 deletions wger/core/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

# Django
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.forms import (
Expand Down Expand Up @@ -51,10 +50,9 @@
Row,
Submit,
)
from django_recaptcha.fields import ReCaptchaField
from django_recaptcha.widgets import ReCaptchaV3

# wger
from wger.core.captcha import captcha_field
from wger.core.models import UserProfile
from wger.core.models.profile import available_timezone_names

Expand Down Expand Up @@ -87,7 +85,7 @@ def __init__(self, *args, **kwargs):
class WgerSignupForm(AllauthSignupForm):
"""
allauth's signup form with wger's password-toggle widgets and an optional
reCAPTCHA field (shown when WGER_SETTINGS['USE_RECAPTCHA'] is set).
CAPTCHA field (see captcha_field).

The crispy helper uses ``form_tag = False`` because both consumers — the
dedicated signup page and the landing page — provide their own ``<form>``.
Expand All @@ -109,12 +107,9 @@ def __init__(self, *args, **kwargs):
css_class='form-row',
),
]
if settings.WGER_SETTINGS['USE_RECAPTCHA']:
self.fields['captcha'] = ReCaptchaField(
widget=ReCaptchaV3(action='register'),
label='reCaptcha',
help_text=gettext_lazy('The form is secured with reCAPTCHA'),
)
captcha = captcha_field('register')
if captcha is not None:
self.fields['captcha'] = captcha
layout_fields.append('captcha')

self.helper = FormHelper()
Expand Down Expand Up @@ -347,20 +342,17 @@ def clean_username(self):

class WgerResetPasswordForm(AllauthResetPasswordForm):
"""
allauth's password reset form with an optional reCAPTCHA field (shown when
WGER_SETTINGS['USE_RECAPTCHA'] is set).
allauth's password reset form with an optional CAPTCHA field (same provider
as the signup form, see captcha_field).
"""

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

layout_fields = ['email']
if settings.WGER_SETTINGS['USE_RECAPTCHA']:
self.fields['captcha'] = ReCaptchaField(
widget=ReCaptchaV3(action='password_reset'),
label='reCaptcha',
help_text=gettext_lazy('The form is secured with reCAPTCHA'),
)
captcha = captcha_field('password_reset')
if captcha is not None:
self.fields['captcha'] = captcha
layout_fields.append('captcha')

self.helper = FormHelper()
Expand Down
2 changes: 2 additions & 0 deletions wger/core/templates/forms/turnstile.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<script src="{{ widget.script_url }}" async defer></script>
<div class="cf-turnstile {{ widget.attrs.class|default:'' }}"{% if widget.attrs.id %} id="{{ widget.attrs.id }}"{% endif %} data-sitekey="{{ widget.site_key }}" data-action="{{ widget.action }}"></div>
Loading
Loading